POI(Apache 专门操作 excel api)
应用场景:
应用于将数据写入excel,用户可以共享数据.作为备份数据(不包括大字段) 还原数据。
例子:
public class POITest { @Test public void testPoi() throws IOException{ //1.创建一个工作簿 workbook HSSFWorkbook wk = new HSSFWorkbook(); //2.创建一个工作表 sheet Sheet sheet=wk.createSheet(); //3.创建一个行对象row(下标起始值为0) Row row = sheet.createRow(3); //4.创建一个单元格对象cell(下标起始值为0) Cell cell = row.createCell(3); //5.给单元格设置内容 cell.setCellValue("好好学习"); //6.设置单元格的样式,设置字体和字体的大小 CellStyle cellStyle = wk.createCellStyle();//创建样式对象 Font font = wk.createFont();//创建字体对象 //设置字体大小 font.setFontHeightInPoints((short)48);//设置字体大小 //设置字体名称 font.setFontName("宋体");//设置字体名称 //在样式对象中设置字体 cellStyle.setFont(font); cell.setCellStyle(cellStyle); //7.保存,关闭流对象 OutputStream os = new FileOutputStream("D:/a.xls"); wk.write(os); os.close(); //8.下载(junit中无法实现) } }
注意:模板打印要先设置要打印的值 不然会出现空指针异常
表格打印第一列留白 方便装订
列宽调用setColumnWidth方法 本身就是个bug
解决方法1: *256 -->还是会有差别(行高缩水最多)
解决方法2:使用别的方法(模板打印)
合并单元格:
Region region = null; region = new Region(curRow-1, (short)(1), curRow-1+3, (short)1); //纵向合并单元格 sheet.addMergedRegion(region); CellRangeAddress sheet.addMergedRegion(new CellRangeAddress(开始行,结束行,开始列,结束列));//横向合并单元格
文件直接输出:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //生成流对象 wb.write(byteArrayOutputStream); //将excel写入流 HttpServletResponse response = ServletActionContext.getResponse(); //工具类,封装弹出下载框: DownloadBaseAction down = new DownloadBaseAction(); down.download(byteArrayOutputStream, response, outFile);
获取模板:
int curRow = 0; //当前行 int colNo = 1; //当前列 //得到模板路径 String rootPath = UtilFuns.getROOTPath(); String xlsFile = rootPath + "/make/xlsprint/tOUTPRODUCT.xls"; //新建临时目录,存放excel /root/web/tmpfile/yyyy-mm-dd/... String filePath = "/web/目录名/" + UtilFuns.sysDate()+"/"; File tmpDir = new File(rootPath + filePath); if(!tmpDir.exists()){ tmpDir.mkdirs(); //创建多级目录 } FileUtil fu = new FileUtil(); String sFile = fu.newFile(rootPath+filePath, "outproduct.xls"); //防止文件并发访问 String outFile = rootPath+filePath+sFile; //输出文件
打印常用样式:
//大标题的样式 public CellStyle bigTitle(Workbook wb){ CellStyle style = wb.createCellStyle(); Font font = wb.createFont(); font.setFontName("宋体"); font.setFontHeightInPoints((short)16); font.setBoldweight(Font.BOLDWEIGHT_BOLD); //字体加粗 style.setFont(font); style.setAlignment(CellStyle.ALIGN_CENTER); //横向居中 style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); //纵向居中 return style; } //小标题的样式 public CellStyle title(Workbook wb){ CellStyle style = wb.createCellStyle(); Font font = wb.createFont(); font.setFontName("黑体"); font.setFontHeightInPoints((short)12); style.setFont(font); style.setAlignment(CellStyle.ALIGN_CENTER); //横向居中 style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); //纵向居中 style.setBorderTop(CellStyle.BORDER_THIN); //上细线 style.setBorderBottom(CellStyle.BORDER_THIN); //下细线 style.setBorderLeft(CellStyle.BORDER_THIN); //左细线 style.setBorderRight(CellStyle.BORDER_THIN); //右细线 return style; } //文字样式 public CellStyle text(Workbook wb){ CellStyle style = wb.createCellStyle(); Font font = wb.createFont(); font.setFontName("Times New Roman"); font.setFontHeightInPoints((short)10); style.setFont(font); style.setAlignment(CellStyle.ALIGN_LEFT); //横向居左 style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); //纵向居中 style.setBorderTop(CellStyle.BORDER_THIN); //上细线 style.setBorderBottom(CellStyle.BORDER_THIN); //下细线 style.setBorderLeft(CellStyle.BORDER_THIN); //左细线 style.setBorderRight(CellStyle.BORDER_THIN); //右细线 return style; }
下载附件名乱码解决:
/** * 下载文件时,针对不同浏览器,进行附件名的编码 * @param filename 下载文件名 * @param agent 客户端浏览器 * @return 编码后的下载附件名 * @throws IOException */ public String encodeDownloadFilename(String filename, String agent) throws IOException{ if(agent.contains("Firefox")){ // 火狐浏览器 filename = "=?UTF-8?B?"+new BASE64Encoder().encode(filename.getBytes("utf-8"))+"?="; }else{ // IE及其他浏览器 filename = URLEncoder.encode(filename,"utf-8"); } return filename; }
文件下载:
文件下载方法1: 先在服务器产生临时文件,再下载临时文件。 关闭保存excel文件 FileOutputStream fOut = new FileOutputStream(xlsFile); //创建xls文件,无内容 0字节 wb.write(fOut); //写内容,xls文件已经可以打开 fOut.flush(); //刷新缓冲区 fOut.close(); //关闭
文件下载方法2: //7.生成excel文件 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //生成流对象 wb.write(byteArrayOutputStream); //将excel写入流 //工具类,封装弹出下载框: String outFile = "生产厂家通讯录.xls"; DownloadBaseAction down = new DownloadBaseAction(); down.download(byteArrayOutputStream, response, outFile);
文件下载方法3:(适用于struts2)ServletActionContext.getResponse().setContentType("application/octet-stream"); String returnName = ServletActionContext.getResponse().encodeURL( new String("购销合同.xls".getBytes(), "ISO-8859-1")); ServletActionContext.getResponse().addHeader("Content-Disposition", "attachment;filename=" + returnName); wb.write(ServletActionContext.getResponse().getOutputStream());
文件下载方法4: //下载文件 response.setContentType("application/octet-stream"); String returnName = response.encodeURL( new String("生产厂家通讯录.xls".getBytes(), "ISO-8859-1")); response.addHeader("Content-Disposition", "attachment;filename=" + returnName); wb.write(response.getOutputStream());
字体:
字体修饰: //设置单元格样式 private HSSFCellStyle leftStyle(HSSFWorkbook wb){ HSSFCellStyle curStyle = wb.createCellStyle(); HSSFFont curFont = wb.createFont(); //设置字体 //curFont.setFontName("Times New Roman"); //设置英文字体 curFont.setFontName("微软雅黑"); //设置英文字体 curFont.setCharSet(HSSFFont.DEFAULT_CHARSET); //设置中文字体,那必须还要再对单元格进行编码设置 curFont.setFontHeightInPoints((short)10); //字体大小 curFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //加粗 curStyle.setFont(curFont); curStyle.setBorderTop(HSSFCellStyle.BORDER_THICK); //粗实线 curStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //实线 curStyle.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM); //比较粗实线 curStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); //实线 curStyle.setWrapText(true); //换行 curStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT); //横向具右对齐 curStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //单元格垂直居中 return curStyle; }
设置打印方向(默认纵向)及宽高:
PrintSetup ps = sheet.getPrintSetup(); ps.setLandscape(true); //横向打印 自适应列宽: //bug 对中文支持不好,列宽不够宽 for(int i=0 ;i<titles.length;i++){ sheet.autoSizeColumn((short)i); } 设置行高: nRow.setHeightInPoints(18); 设置列宽: sheet.setColumnWidth((short)colNo, (short)(256*8)); 设置每列默认宽度: sheet.setDefaultColumnWidth((short) 20); 设置标题: 将第一行作为标题,即每页都打印此行 sheetN,startCol,stopCol,startRow,stopRow wb.setRepeatingRowsAndColumns(0,1,8,0,1); 页脚: HSSFFooter footer = sheet.getFooter(); footer.setRight("第"+HSSFFooter.page()+"页 共"+HSSFFooter.numPages()+"页 "); //页数 工具类-单元格自适应高度: float height = pioUtil.getCellAutoHeight(extcproducts, 12f); nRow.setHeightInPoints(height); //(一行字+行之间的间隙)*行数
分页:
/ POI分页符有BUG,必须在模板文件中插入一个分页符,然后再此处删除预设的分页符;最后在下面重新设置分页符。 // sheet.setAutobreaks(false); // int iRowBreaks[] = sheet.getRowBreaks(); // sheet.removeRowBreak(3); // sheet.removeRowBreak(4); // sheet.removeRowBreak(5); // sheet.removeRowBreak(6); sheet.setRowBreak(行数); //在第startRow行设置分页符
合同打印:
1.分页 sheet.setRowBreak(当前行); //设置分页符 2.怎么插入一个图片 HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); //add picture pioUtil.setPicture(wb, patriarch, rootPath+"make/xlsprint/logo.jpg", curRow, 2, curRow+4, 2); 3.怎么插入一条线 pioUtil.setLine(wb, patriarch, curRow, 2, curRow, 8); //draw line 4.设置数值类型 nCell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); 5、设置前导符 HSSFDataFormat format = wb.createDataFormat(); return format.getFormat("\"¥\"#,###,##0.00"); // 设置格式 6、设置公式 nCell.setCellType(HSSFCell.CELL_TYPE_FORMULA); nCell.setCellFormula("F11*H11"); nCell.setCellFormula("F"+String.valueOf(curRow)+"*H"+String.valueOf(curRow)); nCell.setCellFormula("SUM(I"+String.valueOf(curRow-4)+":I"+String.valueOf(curRow-1)+")"); 7、工具类:替换等量空格 fixSpaceStr(String str,int len) 8、业务要求: 1)同一个厂家的货物才能打印到同一个页面 List<ContractProduct> oList = oDao.find("from ContractProduct o where o.contract.id='"+contractId+"' order by o.factory.id,o.orderNo"); //厂家不同另起新页打印,除去第一次的比较 if(oProduct.getFactory().getFactoryName().equals(oldFactory)){ } 2)打印可以选择打印一款货物,还是两款货物 if(contract.getPrintStyle().equals("2")){ } 9、数据和业务分离 //填写每页的内容,之后在循环每页读取打印 Map<String,String> pageMap = null; List<Map> pageList = new ArrayList(); //打印页 //报运打印: wb.cloneSheet(0); //复制sheet0工作簿,名字会自动重命名
百万级别数据导出:
public class OutProductAction extends BaseAction { // 调用业务逻辑 private ContractProductService contractProductService; public void setContractProductService(ContractProductService contractProductService) { this.contractProductService = contractProductService; } // 封装参数 private String inputDate; public void setInputDate(String inputDate) { this.inputDate = inputDate; } public String toedit() throws Exception { return "toedit"; } /** * excel表格的打印 */ /*public String print() throws Exception { // 1.创建工作簿 // Workbook wb = new HSSFWorkbook();//只支持excel2003 // Workbook wb = new XSSFWorkbook();//支持excel2007及以上版本 Workbook wb = new SXSSFWorkbook(1000); // 支持百万数据的POI 可以带上一个参数:int类型 // 代表内存中对象的个数达到这个指定的值,就会将内存中的这些对象转移到磁盘(临时文件,xml格式) // 这个数字默认是100 // 测试:可能会失败? 25*100----4500000-----1000 // 因为进行磁盘操作时,IO操作也是花时间的,而for循环产生的对象速度比搬移对象的速度快出1000倍 // 2.创建Sheet Sheet sheet = wb.createSheet(); // 设置一些公共变量 Row nRow = null; Cell nCell = null; int rowNo = 0; int cellNO = 1; // 设置列宽 列宽当你调用setColumnWidth本身就是个bug,将来用别的方法改造 sheet.setColumnWidth(0, 1 * 256); sheet.setColumnWidth(1, 26 * 256); sheet.setColumnWidth(2, 11 * 256); sheet.setColumnWidth(3, 29 * 256); sheet.setColumnWidth(4, 12 * 256); sheet.setColumnWidth(5, 15 * 256); sheet.setColumnWidth(6, 10 * 256); sheet.setColumnWidth(7, 10 * 256); sheet.setColumnWidth(8, 8 * 256); // 3.创建行对象--------------------------大标题 nRow = sheet.createRow(rowNo++); // 创建第一行 // 设置行高 nRow.setHeightInPoints(36f); nCell = nRow.createCell(cellNO); // 创建第一行的第二单元格 nCell.setCellValue(inputDate.replace("-0", "-").replace("-", "年") + "月份出货表"); // 2015-01 // 2015-10 // 合并单元格 sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8));// 横向合并单元格 // 设置样式 nCell.setCellStyle(this.bigTitle(wb)); // 4.---------------------------------小标题 nRow = sheet.createRow(rowNo++); // 创建第二行 // 设置行高 nRow.setHeightInPoints(26.25f); String titles[] = { "客户", "订单号", "货号", "数量", "工厂 ", "工厂交期", " 船期", "贸易条款" }; for (String title : titles) { // 生成单元格对象 nCell = nRow.createCell(cellNO++); // 设置单元格的内容 nCell.setCellValue(title); // 设置单元格样式 nCell.setCellStyle(this.title(wb)); } // 5.-------------------------------- 数据行 String hql = "from ContractProduct where to_char(contract.shipTime,'yyyy-MM') ='" + inputDate + "' "; List<ContractProduct> cpList = contractProductService.find(hql, ContractProduct.class, null); for (ContractProduct cp : cpList) { for (int i = 0; i < 1000; i++) { nRow = sheet.createRow(rowNo++);// 数据行 nRow.setHeightInPoints(24f);// 设置行高 cellNO = 1; // 得到单元格对象 客户 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(cp.getContract().getCustomName());// 设置单元格内容 nCell.setCellStyle(this.text(wb)); // 订单号 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(cp.getContract().getContractNo());// 设置单元格内容 nCell.setCellStyle(this.text(wb)); // 货号 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(cp.getProductNo());// 设置单元格内容 nCell.setCellStyle(this.text(wb)); // 数量 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(cp.getCnumber());// 设置单元格内容 nCell.setCellStyle(this.text(wb)); // 工厂 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(cp.getFactoryName());// 设置单元格内容 nCell.setCellStyle(this.text(wb)); // 工厂交期 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(UtilFuns.dateTimeFormat(cp.getContract().getDeliveryPeriod()));// 设置单元格内容 nCell.setCellStyle(this.text(wb)); // 船期 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(UtilFuns.dateTimeFormat(cp.getContract().getShipTime()));// 设置单元格内容 nCell.setCellStyle(this.text(wb)); // 贸易条款 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(cp.getContract().getTradeTerms());// 设置单元格内容 nCell.setCellStyle(this.text(wb)); } } // 将wb中的内容 输出到一个指定的缓存 ByteArrayOutputStream baos = new ByteArrayOutputStream(); wb.write(baos); // 6.文件下载 DownloadUtil downloadUtil = new DownloadUtil(); // 得到Response对象 HttpServletResponse response = ServletActionContext.getResponse(); downloadUtil.download(baos, response, "出货表.xlsx"); return NONE; }*/ /** * 模板打印 * * @return * @throws Exception */ public String print() throws Exception { // 1. 得到模板文件的路径 getRealPath("/")得到应用程序的根路径 String path = ServletActionContext.getServletContext().getRealPath("/") + "/make/xlsprint/tOUTPRODUCT.xlsx"; // 创建一个输入流,用于读取模板文件 InputStream is = new FileInputStream(path); // 1.获取工作簿 // Workbook wb = new HSSFWorkbook(is); //is代表模板文件所对应的流 // HSSFWorkbook只能操作excel2003版 Workbook wb = new XSSFWorkbook(is); // 它只能操作excel2007及以上的版本 // Workbook wb = new SXSSFWorkbook(is); // //它不支持模板打印,操作excel2007及以上版本,它可以支持百万级别的数量导出 // 它实现百万数据的POI的思想是:它是先将内存中产生的过多的对象搬移到磁盘,并清空内存中这些对象,这样就可以有更多的内存空间 // 当poi结束时,又会将磁盘中保存的一些poi对象输出到excel文件中,并清空磁盘中产生的临时 文件 // 2.获取Sheet Sheet sheet = wb.getSheetAt(0);// 获取第一个Sheet // 设置一些公共变量 Row nRow = null; Cell nCell = null; int rowNo = 0; int cellNO = 1; // 3.创建行对象--------------------------大标题 nRow = sheet.getRow(rowNo++); // 创建第一行 // 设置行高 nCell = nRow.getCell(cellNO); // 创建第一行的第二单元格 nCell.setCellValue(inputDate.replace("-0", "-").replace("-", "年") + "月份出货表"); // 2015-01 // 2015-10 // 4.---------------------------------小标题 rowNo++; // 5.-------------------------------- 数据行 // 获取第三行 nRow = sheet.getRow(rowNo); // 读取第三行的每个单元格的样式 String value = nRow.getCell(cellNO).getStringCellValue(); System.out.println(value); CellStyle customerCellStyle = nRow.getCell(cellNO++).getCellStyle();// 客人 CellStyle orderNoCellStyle = nRow.getCell(cellNO++).getCellStyle();// 订单号 CellStyle productNoCellStyle = nRow.getCell(cellNO++).getCellStyle();// 货号 CellStyle cNumberCellStyle = nRow.getCell(cellNO++).getCellStyle();// 数量 CellStyle factoryCellStyle = nRow.getCell(cellNO++).getCellStyle();// 工厂 CellStyle deliveryPeriodCellStyle = nRow.getCell(cellNO++).getCellStyle();// 工厂交期 CellStyle shipTimeCellStyle = nRow.getCell(cellNO++).getCellStyle();// 船期 CellStyle tradeTermsCellStyle = nRow.getCell(cellNO++).getCellStyle();// 贸易条款 String hql = "from ContractProduct where to_char(contract.shipTime,'yyyy-MM') ='" + inputDate + "' "; List<ContractProduct> cpList = contractProductService.find(hql, ContractProduct.class, null); for (ContractProduct cp : cpList) { nRow = sheet.createRow(rowNo++);// 数据行 nRow.setHeightInPoints(24f);// 设置行高 cellNO = 1; // 得到单元格对象 客户 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(cp.getContract().getCustomName());// 设置单元格内容 nCell.setCellStyle(customerCellStyle); // 订单号 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(cp.getContract().getContractNo());// 设置单元格内容 nCell.setCellStyle(orderNoCellStyle); // 货号 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(cp.getProductNo());// 设置单元格内容 nCell.setCellStyle(productNoCellStyle); // 数量 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(cp.getCnumber());// 设置单元格内容 nCell.setCellStyle(cNumberCellStyle); // 工厂 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(cp.getFactoryName());// 设置单元格内容 nCell.setCellStyle(factoryCellStyle); // 工厂交期 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(UtilFuns.dateTimeFormat(cp.getContract().getDeliveryPeriod()));// 设置单元格内容 nCell.setCellStyle(deliveryPeriodCellStyle); // 船期 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(UtilFuns.dateTimeFormat(cp.getContract().getShipTime()));// 设置单元格内容 nCell.setCellStyle(shipTimeCellStyle); // 贸易条款 nCell = nRow.createCell(cellNO++);// 创建单元格对象 nCell.setCellValue(cp.getContract().getTradeTerms());// 设置单元格内容 nCell.setCellStyle(tradeTermsCellStyle); } // 将wb中的内容 输出到一个指定的缓存 ByteArrayOutputStream baos = new ByteArrayOutputStream(); wb.write(baos); // 6.文件下载 DownloadUtil downloadUtil = new DownloadUtil(); // 得到Response对象 HttpServletResponse response = ServletActionContext.getResponse(); downloadUtil.download(baos, response, "出货表.xlsx"); return NONE; } // 大标题的样式 public CellStyle bigTitle(Workbook wb) { CellStyle style = wb.createCellStyle(); Font font = wb.createFont(); font.setFontName("宋体"); font.setFontHeightInPoints((short) 16); font.setBoldweight(Font.BOLDWEIGHT_BOLD); // 字体加粗 style.setFont(font); style.setAlignment(CellStyle.ALIGN_CENTER); // 横向居中 style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); // 纵向居中 return style; } // 小标题的样式 public CellStyle title(Workbook wb) { CellStyle style = wb.createCellStyle(); Font font = wb.createFont(); font.setFontName("黑体"); font.setFontHeightInPoints((short) 12); style.setFont(font); style.setAlignment(CellStyle.ALIGN_CENTER); // 横向居中 style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); // 纵向居中 style.setBorderTop(CellStyle.BORDER_THIN); // 上细线 style.setBorderBottom(CellStyle.BORDER_THIN); // 下细线 style.setBorderLeft(CellStyle.BORDER_THIN); // 左细线 style.setBorderRight(CellStyle.BORDER_THIN); // 右细线 return style; } // 文字样式 public CellStyle text(Workbook wb) { CellStyle style = wb.createCellStyle(); Font font = wb.createFont(); font.setFontName("Times New Roman"); font.setFontHeightInPoints((short) 10); style.setFont(font); style.setAlignment(CellStyle.ALIGN_LEFT); // 横向居左 style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); // 纵向居中 style.setBorderTop(CellStyle.BORDER_THIN); // 上细线 style.setBorderBottom(CellStyle.BORDER_THIN); // 下细线 style.setBorderLeft(CellStyle.BORDER_THIN); // 左细线 style.setBorderRight(CellStyle.BORDER_THIN); // 右细线 return style; } }
注意:
CSV文本格式,带格式的txt,excel直接支持打开。
txt格式比xlsx格式打开速度更快,只是备份大数据的话,可以推荐客户选择txt格式。
要看的话,还是xlsx格式。
多Sheet导出:
public class ExportExcelUtils { /** * @Title: exportExcel * @Description: 导出Excel的方法 * @param workbook * @param sheetNum (sheet的位置,0表示第一个表格中的第一个sheet) * @param sheetTitle (sheet的名称) * @param headers (表格的标题) * @param result (表格的数据) * @param out (输出流) * @throws Exception */ public void exportExcel(HSSFWorkbook workbook, int sheetNum, String sheetTitle, String[] headers, List<List<String>> result, OutputStream out) throws Exception { // 生成一个表格 HSSFSheet sheet = workbook.createSheet(); workbook.setSheetName(sheetNum, sheetTitle, HSSFWorkbook.ENCODING_UTF_16); // 设置表格默认列宽度为20个字节 sheet.setDefaultColumnWidth((short) 20); // 生成一个样式 HSSFCellStyle style = workbook.createCellStyle(); // 设置这些样式 style.setFillForegroundColor(HSSFColor.PALE_BLUE.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 生成一个字体 HSSFFont font = workbook.createFont(); font.setColor(HSSFColor.BLACK.index); font.setFontHeightInPoints((short) 12); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 把字体应用到当前的样式 style.setFont(font); // 指定当单元格内容显示不下时自动换行 style.setWrapText(true); // 产生表格标题行 HSSFRow row = sheet.createRow(0); for (int i = 0; i < headers.length; i++) { HSSFCell cell = row.createCell((short) i); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text.toString()); } // 遍历集合数据,产生数据行 if (result != null) { int index = 1; for (List<String> m : result) { row = sheet.createRow(index); int cellIndex = 0; for (String str : m) { HSSFCell cell = row.createCell((short) cellIndex); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(str.toString()); cellIndex++; } index++; } } } }
测试数据:(在D盘下生成test.xls文件,并有多个sheet)
public class PoiTest { public static void main(String[] args) { try { OutputStream out = new FileOutputStream("D:\\test.xls"); List<List<String>> data = new ArrayList<List<String>>(); for (int i = 1; i < 5; i++) { List rowData = new ArrayList(); rowData.add(String.valueOf(i)); rowData.add("itcast"); data.add(rowData); } String[] headers = { "ID", "用户名" }; ExportExcelUtils eeu = new ExportExcelUtils(); HSSFWorkbook workbook = new HSSFWorkbook(); eeu.exportExcel(workbook, 0, "上海", headers, data, out); eeu.exportExcel(workbook, 1, "深圳", headers, data, out); eeu.exportExcel(workbook, 2, "广州", headers, data, out); //原理就是将所有的数据一起写入,然后再关闭输入流。 workbook.write(out); out.close(); } catch (Exception e) { e.printStackTrace(); } } }