POI操作Excel详解,HSSF和XSSF两种方式

HSSF方式:

package com.tools.poi.lesson1;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;

import com.tools.poi.bean.Student;

public class ExcelUtilWithHSSF {
	public static void main(String[] args) {
		try {
			getExcelAsFile("aaa");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
//		try {
//			CreateExcelDemo1();
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
		
		
	}
	
	/**
	 * 得到Excel,并解析内容
	 * @param file
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void getExcelAsFile(String file) throws FileNotFoundException, IOException{
		//1.得到Excel常用对象
//		POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/FTP/test.xls"));
		POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/FTP/new1.xls"));
		//2.得到Excel工作簿对象
		HSSFWorkbook wb = new HSSFWorkbook(fs);
		//3.得到Excel工作表对象
		HSSFSheet sheet = wb.getSheetAt(0);
		//总行数
		int trLength = sheet.getLastRowNum();
		//4.得到Excel工作表的行
		HSSFRow row = sheet.getRow(0);
		//总列数
		int tdLength = row.getLastCellNum();
		//5.得到Excel工作表指定行的单元格
		HSSFCell cell = row.getCell((short)1);
		//6.得到单元格样式
		CellStyle cellStyle = cell.getCellStyle();
		for(int i=0;i<trLength;i++){
			//得到Excel工作表的行
			HSSFRow row1 = sheet.getRow(i);
			for(int j=0;j<tdLength;j++){
				
			//得到Excel工作表指定行的单元格
			HSSFCell cell1 = row1.getCell(j);
			
			/**
			 * 为了处理:Excel异常Cannot get a text value from a numeric cell
			 * 将所有列中的内容都设置成String类型格式
			 */
			if(cell1!=null){
		          cell1.setCellType(Cell.CELL_TYPE_STRING);
		     }
			
			//获得每一列中的值
			System.out.print(cell1.getStringCellValue()+"\t\t\t");
			}
			System.out.println();
		}
	}
	
	
	/**
	 * 创建Excel,并写入内容
	 */
	public static void CreateExcel(){
		
		//1.创建Excel工作薄对象
		HSSFWorkbook wb = new HSSFWorkbook();
		//2.创建Excel工作表对象     
		HSSFSheet sheet = wb.createSheet("new Sheet");
		//3.创建Excel工作表的行   
		HSSFRow row = sheet.createRow(6);
		//4.创建单元格样式
		CellStyle cellStyle =wb.createCellStyle();
	      // 设置这些样式
		cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
		cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
		cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	      
	      
	      
		//5.创建Excel工作表指定行的单元格
		row.createCell(0).setCellStyle(cellStyle);
		//6.设置Excel工作表的值
		row.createCell(0).setCellValue("aaaa");
		
		row.createCell(1).setCellStyle(cellStyle);
		row.createCell(1).setCellValue("bbbb");
		
		
		//设置sheet名称和单元格内容
		wb.setSheetName(0,"第一张工作表");
		//设置单元格内容	cell.setCellValue("单元格内容");
		
		// 最后一步,将文件存到指定位置
				try
				{
					FileOutputStream fout = new FileOutputStream("E:/students.xls");
					wb.write(fout);
					fout.close();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
	}
	
	/**
	 * 创建Excel的实例
	 * @throws ParseException 
	 */
	public static void CreateExcelDemo1() throws ParseException{
		List list = new ArrayList();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");
		Student user1 = new Student(1, "张三", 16,true, df.parse("1997-03-12"));
		Student user2 = new Student(2, "李四", 17,true, df.parse("1996-08-12"));
		Student user3 = new Student(3, "王五", 26,false, df.parse("1985-11-12"));
		list.add(user1);
		list.add(user2);
		list.add(user3);
		
		
		// 第一步,创建一个webbook,对应一个Excel文件
				HSSFWorkbook wb = new HSSFWorkbook();
				// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
				HSSFSheet sheet = wb.createSheet("学生表一");
				// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
				HSSFRow row = sheet.createRow((int) 0);
				// 第四步,创建单元格,并设置值表头 设置表头居中
				HSSFCellStyle style = wb.createCellStyle();
				style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

				HSSFCell cell = row.createCell((short) 0);
				cell.setCellValue("学号");
				cell.setCellStyle(style);
				cell = row.createCell((short) 1);
				cell.setCellValue("姓名");
				cell.setCellStyle(style);
				cell = row.createCell((short) 2);
				cell.setCellValue("年龄");
				cell.setCellStyle(style);
				cell = row.createCell((short) 3);
				cell.setCellValue("性别");
				cell.setCellStyle(style);
				cell = row.createCell((short) 4);
				cell.setCellValue("生日");
				cell.setCellStyle(style);

				// 第五步,写入实体数据 实际应用中这些数据从数据库得到,

				for (int i = 0; i < list.size(); i++)
				{
					row = sheet.createRow((int) i + 1);
					Student stu = (Student) list.get(i);
					// 第四步,创建单元格,并设置值
					row.createCell((short) 0).setCellValue((double) stu.getId());
					row.createCell((short) 1).setCellValue(stu.getName());
					row.createCell((short) 2).setCellValue((double) stu.getAge());
					row.createCell((short)3).setCellValue(stu.getSex()==true?"男":"女");
					cell = row.createCell((short) 4);
					cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu
							.getBirthday()));
				}
				// 第六步,将文件存到指定位置
				try
				{
					FileOutputStream fout = new FileOutputStream("E:/students.xls");
					wb.write(fout);
					fout.close();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
		
		
		
	}
}

XSSF方式:

package com.tools.poi.lesson1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.WorkbookUtil;

import com.tools.poi.bean.Student;

public class ExcelUtilWithXSSF {
	public static void main(String[] args) {
		try {
			getExcelAsFile("d:/FTP/系统报表.xls");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			e.printStackTrace();
		}
		
		
//		try {
//			CreateExcelDemo1();
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
		
		
	}
	
	/**
	 * 得到Excel,并解析内容  对2007及以上版本 使用XSSF解析
	 * @param file
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @throws InvalidFormatException 
	 */
	public static void getExcelAsFile(String file) throws FileNotFoundException, IOException, InvalidFormatException{
//		//1.得到Excel常用对象
//		POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/FTP/new1.xls"));
//		//2.得到Excel工作簿对象
//		HSSFWorkbook wb = new HSSFWorkbook(fs);

		
		
		InputStream ins = null;   
        Workbook wb = null;   
            ins=new FileInputStream(new File(file));   
            //ins= ExcelService.class.getClassLoader().getResourceAsStream(filePath);   
            wb = WorkbookFactory.create(ins);   
            ins.close();   
		
		
		//3.得到Excel工作表对象
		Sheet sheet = wb.getSheetAt(0);
		//总行数
		int trLength = sheet.getLastRowNum();
		//4.得到Excel工作表的行
		Row row = sheet.getRow(0);
		//总列数
		int tdLength = row.getLastCellNum();
		//5.得到Excel工作表指定行的单元格
		Cell cell = row.getCell((short)1);
		//6.得到单元格样式
		CellStyle cellStyle = cell.getCellStyle();

		for(int i=5;i<trLength;i++){
			//得到Excel工作表的行
			Row row1 = sheet.getRow(i);
			for(int j=0;j<tdLength;j++){
			//得到Excel工作表指定行的单元格
			Cell cell1 = row1.getCell(j);
			/**
			 * 为了处理:Excel异常Cannot get a text value from a numeric cell
			 * 将所有列中的内容都设置成String类型格式
			 */
			if(cell1!=null){
		          cell1.setCellType(Cell.CELL_TYPE_STRING);
		     }
			
			if(j==5&&i<=10){
				cell1.setCellValue("1000");
			}
			
			//获得每一列中的值
			System.out.print(cell1+"                   ");
			}
			System.out.println();
		}
		
		//将修改后的数据保存
		OutputStream out = new FileOutputStream(file);
                wb.write(out);
	}
	
	
	/**
	 * 创建Excel,并写入内容
	 */
	public static void CreateExcel(){
		
		//1.创建Excel工作薄对象
		HSSFWorkbook wb = new HSSFWorkbook();
		//2.创建Excel工作表对象     
		HSSFSheet sheet = wb.createSheet("new Sheet");
		//3.创建Excel工作表的行   
		HSSFRow row = sheet.createRow(6);
		//4.创建单元格样式
		CellStyle cellStyle =wb.createCellStyle();
	      // 设置这些样式
		cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
		cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
		cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	      
	      
	      
		//5.创建Excel工作表指定行的单元格
		row.createCell(0).setCellStyle(cellStyle);
		//6.设置Excel工作表的值
		row.createCell(0).setCellValue("aaaa");
		
		row.createCell(1).setCellStyle(cellStyle);
		row.createCell(1).setCellValue("bbbb");
		
		
		//设置sheet名称和单元格内容
		wb.setSheetName(0,"第一张工作表");
		//设置单元格内容	cell.setCellValue("单元格内容");
		
		// 最后一步,将文件存到指定位置
				try
				{
					FileOutputStream fout = new FileOutputStream("E:/students.xls");
					wb.write(fout);
					fout.close();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
	}
	
	/**
	 * 创建Excel的实例
	 * @throws ParseException 
	 */
	public static void CreateExcelDemo1() throws ParseException{
		List list = new ArrayList();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");
		Student user1 = new Student(1, "张三", 16,true, df.parse("1997-03-12"));
		Student user2 = new Student(2, "李四", 17,true, df.parse("1996-08-12"));
		Student user3 = new Student(3, "王五", 26,false, df.parse("1985-11-12"));
		list.add(user1);
		list.add(user2);
		list.add(user3);
		
		
		// 第一步,创建一个webbook,对应一个Excel文件
				HSSFWorkbook wb = new HSSFWorkbook();
				// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
				HSSFSheet sheet = wb.createSheet("学生表一");
				// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
				HSSFRow row = sheet.createRow((int) 0);
				// 第四步,创建单元格,并设置值表头 设置表头居中
				HSSFCellStyle style = wb.createCellStyle();
				style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

				HSSFCell cell = row.createCell((short) 0);
				cell.setCellValue("学号");
				cell.setCellStyle(style);
				cell = row.createCell((short) 1);
				cell.setCellValue("姓名");
				cell.setCellStyle(style);
				cell = row.createCell((short) 2);
				cell.setCellValue("年龄");
				cell.setCellStyle(style);
				cell = row.createCell((short) 3);
				cell.setCellValue("性别");
				cell.setCellStyle(style);
				cell = row.createCell((short) 4);
				cell.setCellValue("生日");
				cell.setCellStyle(style);

				// 第五步,写入实体数据 实际应用中这些数据从数据库得到,

				for (int i = 0; i < list.size(); i++)
				{
					row = sheet.createRow((int) i + 1);
					Student stu = (Student) list.get(i);
					// 第四步,创建单元格,并设置值
					row.createCell((short) 0).setCellValue((double) stu.getId());
					row.createCell((short) 1).setCellValue(stu.getName());
					row.createCell((short) 2).setCellValue((double) stu.getAge());
					row.createCell((short)3).setCellValue(stu.getSex()==true?"男":"女");
					cell = row.createCell((short) 4);
					cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu
							.getBirthday()));
				}
				// 第六步,将文件存到指定位置
				try
				{
					FileOutputStream fout = new FileOutputStream("E:/students.xls");
					wb.write(fout);
					fout.close();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
		
		
		
	}
}

注意:

修改Excel中的某个内容:

cell1.setCellValue("1000");

保存修改后的Excel文件:

OutputStream out = new FileOutputStream(file);
wb.write(out);

轉自【http://blog.csdn.net/he90227/article/details/37563497】

  • 9
    点赞
  • 79
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!关于您的问题,我可以给您提供一些参考信息。 Java POI是一个开源的Java API,可以用于读取和操作Excel文件。它提供了许多用于在Excel中插入图像、文本、数字、图表和其他元素的方法。 要在Excel中画线,可以使用Java POI中的HSSFDrawing类。HSSFDrawing类是HSSF工作簿中所有绘图对象的基类。您可以使用此类来添加各种绘图对象,例如线条、箭头、形状、文本框等。 以下是一个简单的示例代码,展示如何在Excel中画一条红色的线: ``` import java.io.FileOutputStream; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFDrawing; import org.apache.poi.hssf.usermodel.HSSFShape; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; import org.apache.poi.ss.usermodel.ShapeTypes; public class DrawLineInExcel { public static void main(String[] args) throws Exception { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Line Sheet"); HSSFDrawing drawing = sheet.createDrawingPatriarch(); HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 5, 5); anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); HSSFShape shape = drawing.createShape(anchor, ShapeTypes.LINE); shape.setLineWidth(2); shape.setLineStyleColor(255, 0, 0); FileOutputStream fileOut = new FileOutputStream("line.xlsx"); workbook.write(fileOut); fileOut.close(); System.out.println("Line drawn successfully!"); } } ``` 此代码将创建一个新的Excel工作簿,并在名称为“Line Sheet”的工作表中绘制一条线。然后将工作簿写入名为“line.xlsx”的文件中。 希望这可以帮助您开始解决问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值