使用poi操作excel

本文介绍了如何使用Apache POI库在Java中操作Microsoft Excel文件。内容包括POI库的简介、API文档的查阅方式、针对不同Excel版本所需jar包的说明,以及通过HSSFWorkbook、HSSFSheet、HSSFRow和HSSFCell等对象进行写入和读取Excel的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

POI全称 Poor ObfuscationImplementation,直译为“可怜的模糊实现”,利用POI接口可以通过JAVA操作Microsoft office 套件工具的读写功能。官网:http://poi.apache.org ,POI支持office的所有版本

在“poi-bin-3.10.1-20140818\poi-3.10.1\docs\apidocs”目录中,点击“index.html”查看POI api文档,我们可以查询POI中所有这些对象的属性和方法。

 

对于只操作2003 及以前版本的excel,只需要poi-3.10.1-20140818.jar,

如果需要同时对2007及以后版本进行操作则需要复制

         poi-ooxml-3.10.1-20140818.jar,

         poi-ooxml-schemas-3.10.1-20140818.jar,

以及复制在ooxml-lib目录下的xmlbeans-2.6.0.jar,dom4j-1.6.1.jar。

注意excel03版本文件后缀为.xls,excel07版本文件后缀为.xlsx

 

在POI包中有如下几个主要对象和excel的几个对象对应:

         HSSFWorkbook             Excel 工作簿workbook

         HSSFSheet                   Excel 工作表 sheet

         HSSFRow                     Excel 行

         HSSFCell                      Excel 列


测试代码如下:

(1) 写excel:

        @Test
	public void testWrite2Excel() throws Exception {
		//1、创建工作簿
		HSSFWorkbook workbook = new HSSFWorkbook();
		//2、创建工作表
		HSSFSheet sheet = workbook.createSheet("hello world");//指定工作表名
		//3、创建行;创建第3行
		HSSFRow row = sheet.createRow(2);
		//4、创建单元格;创建第3行第3列
		HSSFCell cell = row.createCell(2);
		cell.setCellValue("Hello World");
		
		//输出到硬盘
		FileOutputStream outputStream = new FileOutputStream("D:\\测试.xls");//07版本后缀改为.xlsx
		//把excel输出到具体的地址
		workbook.write(outputStream);
		workbook.close();
		outputStream.close();
	}

(2) 读excel

        @Test
	public void testRead03And07Excel() throws Exception {
		String fileName = "D:\\测试.xlsx";
		if(fileName.matches("^.+\\.(?i)((xls)|(xlsx))$")){//判断是否excel文档
			
			boolean is03Excel = fileName.matches("^.+\\.(?i)(xls)$");
			
			FileInputStream inputStream = new FileInputStream(fileName);
			
			//1、读取工作簿
			Workbook workbook = is03Excel ?new HSSFWorkbook(inputStream):new XSSFWorkbook(inputStream);
			//2、读取第一个工作表
			Sheet sheet = workbook.getSheetAt(0);
			//3、读取行;读取第3行
			Row row = sheet.getRow(2);
			//4、读取单元格;读取第3行第3列
			Cell cell = row.getCell(2);
			System.out.println("第3行第3列单元格的内容为:" + cell.getStringCellValue());
			
			workbook.close();
			inputStream.close();
		}
	}
(3)  添加样式,合并单元格,字体,背景

        @Test
	public void testExcelStyle() throws Exception {
 		//1、创建工作簿
 		HSSFWorkbook workbook = new HSSFWorkbook();
		//1.1、创建合并单元格对象;合并第3行的第3列到第5列
		CellRangeAddress cellRangeAddress = new CellRangeAddress(2, 2, 2, 4);//起始行号,结束行号,起始列号,结束列号
		 //1.2、创建单元格样式
		HSSFCellStyle style = workbook.createCellStyle();
		 style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
		//1.3、创建字体
		HSSFFont font = workbook.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗字体
		font.setFontHeightInPoints((short) 16);//设置字体大小
		 //加载字体
		style.setFont(font);
		
		//单元格背景
		//设置背景填充模式
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		//设置填充背景色
		style.setFillBackgroundColor(HSSFColor.YELLOW.index);
		//设置填充前景色
		style.setFillForegroundColor(HSSFColor.RED.index);
		
		//2、创建工作表
		HSSFSheet sheet = workbook.createSheet("Hello World");//指定工作表名
		//2.1、加载合并单元格对象
		sheet.addMergedRegion(cellRangeAddress);
		
		//3、创建行;创建第3行
		HSSFRow row = sheet.createRow(2);
		 //4、创建单元格;创建第3行第3列
		HSSFCell cell = row.createCell(2);
		//加载样式
		cell.setCellStyle(style);
		cell.setCellValue("Hello World!");
		
		//输出到硬盘
		FileOutputStream outputStream = new FileOutputStream("D:\\测试.xls");
		//把excel输出到具体的地址
		workbook.write(outputStream);
		workbook.close();
		outputStream.close();
	}
(4)  实际运用---导出

       //导出用户列表 controller层
 	public void exportExcel(){
		try {
			//1、查找用户列表
			//2、导出
			 HttpServletResponse response = ServletActionContext.getResponse();
 			response.setContentType("application/x-execl");
 			response.setHeader("Content-Disposition", "attachment;filename=" + new String("用户列表.xls".getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			userService.exportExcel(userService.findUserList(), outputStream);
			if(outputStream != null){
 				outputStream.close();
			}
		 } catch (Exception e) {
			e.printStackTrace();
		}
	}
UserService
      ExcelUtil.exportUserExcel(userList, outputStream);
ExcelUtil中
      public static void exportUserExcel(List<User> userList, ServletOutputStream outputStream) {
		 try {
  			//1、创建工作簿
			 HSSFWorkbook workbook = new HSSFWorkbook();
 			//1.1、创建合并单元格对象
			 CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 4);//起始行号,结束行号,起始列号,结束列号
			//1.2、头标题样式
			 HSSFCellStyle style1 = createCellStyle(workbook, (short)16);
			//1.3、列标题样式
			 HSSFCellStyle style2 = createCellStyle(workbook, (short)13);
			//2、创建工作表
 			HSSFSheet sheet = workbook.createSheet("用户列表");
			//2.1、加载合并单元格对象
 			sheet.addMergedRegion(cellRangeAddress);
			//设置默认列宽
			sheet.setDefaultColumnWidth(25);
			// sheet.setColumnWidth(0, 1*278);  //具体设置某一列的列狂,设置列宽 256,BUG,精度不够,总是差一点


			//3、创建行
			//3.1、创建头标题行;并且设置头标题
			HSSFRow row1 = sheet.createRow(0);
			HSSFCell cell1 = row1.createCell(0);
                      //row1.setHeightInPoints(36); //设置行高
                        //加载单元格样式
			cell1.setCellStyle(style1);
			cell1.setCellValue("用户列表");
			
			//3.2、创建列标题行;并且设置列标题
			HSSFRow row2 = sheet.createRow(1);
			String[] titles = {"用户名","帐号", "所属部门", "性别", "电子邮箱"};
			for(int i = 0; i < titles.length; i++){
				HSSFCell cell2 = row2.createCell(i);
				//加载单元格样式
				cell2.setCellStyle(style2);
				cell2.setCellValue(titles[i]);
			}
			
			//4、操作单元格;将用户列表写入excel
			if(userList != null){
				for(int j = 0; j < userList.size(); j++){
					HSSFRow row = sheet.createRow(j+2);
					HSSFCell cell11 = row.createCell(0);
					cell11.setCellValue(userList.get(j).getName());
					HSSFCell cell12 = row.createCell(1);
					cell12.setCellValue(userList.get(j).getAccount());
					HSSFCell cell13 = row.createCell(2);
					cell13.setCellValue(userList.get(j).getDept());
					HSSFCell cell14 = row.createCell(3);
					cell14.setCellValue(userList.get(j).isGender()?"男":"女");
					HSSFCell cell15 = row.createCell(4);
					cell15.setCellValue(userList.get(j).getEmail());
				}
			}
			//5、输出
			workbook.write(outputStream);
			workbook.close();
		} catch (Exception e) {
			e.printStackTrace();
		 }
	}

	/**
	 * 创建单元格样式
	 * @param workbook 工作簿
	 * @param fontSize 字体大小
	 * @return 单元格样式
	 */
	private static HSSFCellStyle createCellStyle(HSSFWorkbook workbook, short fontSize) {
		HSSFCellStyle style = workbook.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
		//创建字体
		HSSFFont font = workbook.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗字体
		font.setFontHeightInPoints(fontSize);
		//加载字体
		style.setFont(font);
		return style;
	}

(5) 实际运用--导入

        //导入用户列表  Controller
	public String importExcel(){
		//1、获取excel文件
		if(userExcel != null){
			//是否是excel
			if(userExcelFileName.matches("^.+\\.(?i)((xls)|(xlsx))$")){
				//2、导入
				userService.importExcel(userExcel, userExcelFileName);
			}
		}
		return "list";
	}
        //UserService
        public void importExcel(File userExcel, String userExcelFileName) {
		try {
			FileInputStream fileInputStream = new FileInputStream(userExcel);
			boolean is03Excel = userExcelFileName.matches("^.+\\.(?i)(xls)$");
			//1、读取工作簿
			Workbook workbook = is03Excel ? new HSSFWorkbook(fileInputStream):new XSSFWorkbook(fileInputStream);
			//2、读取工作表
			Sheet sheet = workbook.getSheetAt(0);
			//3、读取行
			if(sheet.getPhysicalNumberOfRows() > 2){
				User user = null;
				for(int k = 2; k < sheet.getPhysicalNumberOfRows(); k++){
					//4、读取单元格
					Row row = sheet.getRow(k);
					user = new User();
					//用户名
					Cell cell0 = row.getCell(0);
					user.setName(cell0.getStringCellValue());
					//帐号
					Cell cell1 = row.getCell(1);
					user.setAccount(cell1.getStringCellValue());
					//所属部门
					Cell cell2 = row.getCell(2);
					user.setDept(cell2.getStringCellValue());
					//性别
					Cell cell3 = row.getCell(3);
					user.setGender(cell3.getStringCellValue().equals("男"));
					//手机号
					String mobile = "";
					Cell cell4 = row.getCell(4);
					<span style="color:#330099;">try {
						mobile = cell4.getStringCellValue();
					} catch (Exception e) {
						double dMobile = cell4.getNumericCellValue();
						mobile = BigDecimal.valueOf(dMobile).toString();
					}</span>
					user.setMobile(mobile);
					
					//电子邮箱
					 Cell cell5 = row.getCell(5);
					 user.setEmail(cell5.getStringCellValue());
					//生日
					Cell cell6 = row.getCell(6);
					if(cell6.getDateCellValue() != null){
						user.setBirthday(cell6.getDateCellValue());
					}
					 //默认用户密码为 123456
					 user.setPassword("123456");
					//默认用户状态为 有效
					user.setState(User.USER_STATE_VALID);
					
					//5、保存用户
					save(user);
				}
			}
			workbook.close();
			fileInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
(6) 实际运用--基于模版开发

读取模版文件的样式,添加到自己新加的单元格中

	//模板开发
	public void printHSSF(String inputDate, HttpServletRequest request, HttpServletResponse response) throws IOException{
		//linux下jdk1.8 方法获取时,不会拼接自己写的目录 
		String path = request.getSession().getServletContext().getRealPath("/") + "/template/";
		InputStream is = new FileInputStream(new File(path + "exce01.xls"));
		
		Workbook wb = new HSSFWorkbook(is);		//打开一个模板文件,工作簿
		 Sheet sheet = wb.getSheetAt(0);			//获取到第一个工作表
		
		 Row nRow = null;
		 Cell nCell = null;
		  int rowNo = 0;							//行号
		  int colNo = 1;							//列号
		
		//获取模板上的单元格样式
 		nRow = sheet.getRow(2);
		
		
		//订单号的样式
		 nCell = nRow.getCell(0);
		 CellStyle contractNoStyle = nCell.getCellStyle();		
		
		
                 //.......
		
		
		//处理内容
		//...给每一个单元格添加样式
		
		//输出
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		 wb.write(os);
		
		DownloadUtil downloadUtil = new DownloadUtil();				//直接弹出下载框,用户可以打开,可以保存
		downloadUtil.download(os, response, "excel表格.xls");
		
		os.flush();
		os.close();
	}
<pre name="code" class="java">DownloadUtil :
public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException{response.setContentType("application/octet-stream;charset=utf-8");returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1")); //保存的文件名,必须和页面编码一致,否则乱码response.addHeader("Content-Disposition", "attachment;filename=" + returnName); response.setContentLength(byteArrayOutputStream.size());ServletOutputStream outputstream = response.getOutputStream(); //取得输出流byteArrayOutputStream.writeTo(outputstream); //写到输出流byteArrayOutputStream.close(); //关闭outputstream.flush(); //刷数据}

 






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值