Java导出Excel和CSV的简单实现,分别使用POI和JavaCSV。
JavaBean
1 public classReportInfo { 2 3 intid; 4 String date; 5 intnum; 6 intpercent; 7 8 public intgetId() { 9 returnid; 10 } 11 public void setId(intid) { 12 this.id =id; 13 } 14 publicString getDate() { 15 returndate; 16 } 17 public voidsetDate(String date) { 18 this.date =date; 19 } 20 public intgetNum() { 21 returnnum; 22 } 23 public void setNum(intnum) { 24 this.num =num; 25 } 26 public intgetPercent() { 27 returnpercent; 28 } 29 public void setPercent(intpercent) { 30 this.percent =percent; 31 } 32 33 }
工具类的简单实现
public classExportUtil { public static void main(String[] args) throwsFileNotFoundException, IOException{ List<ReportInfo> list = new ArrayList<ReportInfo>(); createData(list); exportCSV(list, "/tmp/report.csv"); exportExcel(list, "/tmp/report.xls"); } public static void exportCSV(List<ReportInfo> list, String filePath) throwsIOException{ File file = newFile(filePath); if(file.exists()) file.delete(); CsvWriter wr = new CsvWriter(filePath, ',', Charset.forName("UTF-8")); String[] contents = {"No", "date", "num", "percent"}; wr.writeRecord(contents); ReportInfo info = newReportInfo(); for(int i = 0; i < list.size(); i++){ info =list.get(i); contents[0] =String.valueOf(info.getId()); contents[1] =info.getDate(); contents[2] =String.valueOf(info.getNum()); contents[3] = info.getPercent() + "%"; wr.writeRecord(contents); } wr.close(); } public static void exportExcel(List<ReportInfo> list, String filePath) throwsIOException{ File file = new File(filePath);//"/tmp/tmpfiles/workbook.xls" if(file.exists()) file.delete(); FileOutputStream fileOut = new FileOutputStream(filePath);//创建excel表格//"/tmp/tmpfiles/workbook.xls" Workbook wb = new HSSFWorkbook();//获取workbook //FileOutputStream fileOut = new FileOutputStream("workbook.xls"); HSSFSheet sheet = (HSSFSheet) wb.createSheet("report");//生成一个表格 sheet.setColumnWidth(1, 4000); HSSFRow row = sheet.createRow((short)0);//创建行并插入表头 row.createCell(0).setCellValue("No"); row.createCell(1).setCellValue("date"); row.createCell(2).setCellValue("num"); row.createCell(3).setCellValue("percent"); ReportInfo info = newReportInfo(); for(int i = 1; i <= list.size(); i++){//循环插入数据 info = list.get(i-1); row =sheet.createRow(i); row.createCell(0).setCellValue(info.getId()); row.createCell(1).setCellValue(info.getDate()); row.createCell(2).setCellValue(info.getNum()); row.createCell(3).setCellValue(info.getPercent()+"%"); } wb.write(fileOut); fileOut.close(); } public static void createData(List<ReportInfo>list){ ReportInfo tp = newReportInfo(); tp.setId(1); tp.setNum(2); tp.setPercent(50); tp.setDate("2013-08-20"); list.add(tp); } }
后来看到xwdreamer的一篇文章,使用了Java的泛型和反射将JavaBean的属性依次填充到Excel行中,如能自由指定JavaBean的属性所在列效果更好。
POI的官方快速入门示例:http://poi.apache.org/spreadsheet/quick-guide.html