使用POI生成Excel报表 (三)

2014-11-24 10:18:58 · 作者: · 浏览: 3
.allCellStyle.get(99)); } cell.setCellValue(value); this.currColIndex++; } /** * 插入序号 */ private void insertSerialNo(){ int index = 1; Row row = null; Cell cell = null; for(int i=this.initRowIndex; i constantData = new HashMap(); constantData.put("title", "优秀学生名单"); constantData.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); constantData.put("developer", "玄玉博客"); for(Row row : sheet){ for(Cell cell : row){ if(Cell.CELL_TYPE_STRING != cell.getCellType()){ continue; } String str = cell.getStringCellValue().trim(); if(str.startsWith("#")){ if(constantData.containsKey(str.substring(1))){ cell.setCellValue(constantData.get(str.substring(1))); } } } } } /** * 将生成的excel文件写到输出流中 * @see 适用于文件下载 */ public void writeToStream(OutputStream os){ this.insertSerialNo(); this.replaceConstantData(); try { wb.write(os); } catch (IOException e) { throw new RuntimeException("写入流失败", e); } } /** * 将生成的excel文件写到指定的文件中 * @see 适用于硬盘保存 */ public void writeToFile(String filepath){ this.insertSerialNo(); this.replaceConstantData(); FileOutputStream fos = null; try { fos = new FileOutputStream(filepath); wb.write(fos); } catch (FileNotFoundException e) { throw new RuntimeException("写入的文件[" + filepath + "]不存在", e); } catch (IOException e) { throw new RuntimeException("写入数据失败", e); } finally { if(null != fos){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }


最后是其单元测试类ExcelReportTest.java(即演示实际调用步骤)


package com.jadyer.report; 
 
import java.io.File; 
 
import org.junit.Assert; 
import org.junit.Test; 
 
import com.jadyer.report.ExcelReport; 
 
public class ExcelReportTest { 
    @Test 
    public void testExcelReportUtil(){ 
        ExcelReport eru = ExcelReport.INSTANCE; 
        eru.createNewRow(); 
        eru.buildCell("aa"); 
        eru.buildCell("玄玉"); 
        eru.buildCell("cc"); 
        eru.buildCell("dd"); 
        eru.createNewRow(); 
        eru.buildCell("aa"); 
        eru.buildCell("http://blog.csdn.net/jadyer"); 
        eru.buildCell("cc"); 
        eru.buildCell("dd"); 
        eru.createNewRow(); 
        eru.buildCell("aa"); 
        eru.buildCell("蓄机而动"); 
        eru.buildCell("cc"); 
        eru.buildCell("dd"); 
        eru.writeToFile("D:/test.xls"); 
        Assert.assertTrue(new File("D:/test.xls").exists()); 
    } 
}