Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能
1.下载开发包解压:
2.引入POI的依赖:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.11</version> </dependency>
3.POI使用:
public String exportXls() throws IOException{ List<Subarea> list = subareaService.findAll(); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("分区数据"); HSSFRow row0 = sheet.createRow(0); row0.createCell(0).setCellValue("分区编号"); row0.createCell(1).setCellValue("开始编号"); row0.createCell(2).setCellValue("结束编号"); row0.createCell(3).setCellValue("位置信息"); row0.createCell(4).setCellValue("省市区"); for (Subarea subarea : list) { HSSFRow row = sheet.createRow(sheet.getLastRowNum()+1); row.createCell(0).setCellValue(subarea.getId()); row.createCell(1).setCellValue(subarea.getStartnum()); row.createCell(2).setCellValue(subarea.getEndnum()); row.createCell(3).setCellValue(subarea.getPosition()); row.createCell(4).setCellValue(subarea.getRegion().getName()); } String filename = "分区数据.xls"; String mimeType = ServletActionContext.getServletContext().getMimeType(filename); ServletActionContext.getResponse().setContentType(mimeType); String agent = ServletActionContext.getRequest().getHeader("User-Agent"); filename = FileUtils.encodeDownloadFilename(filename, agent); ServletActionContext.getResponse().setHeader("content-disposition","attchment;filename="+filename); ServletOutputStream out = ServletActionContext.getResponse().getOutputStream(); workbook.write(out); return NONE; }
@Test public void test1() throws FileNotFoundException, IOException{ String filePath = "C:\Users\zhaoqx\Desktop\资料\区域导入测试数据.xls"; //包装一个Excel文件对象 HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(new File(filePath))); //读取文件中第一个Sheet标签页 HSSFSheet hssfSheet = workbook.getSheetAt(0); //遍历标签页中所有的行 for (Row row : hssfSheet) { System.out.println(); for (Cell cell : row) { String value = cell.getStringCellValue(); System.out.print(value + " "); } } }