Java导出Excel表格

匿名 (未验证) 提交于 2019-12-02 21:45:52

Java导出Excel表格

导出Excel表格需要一个poi-3.9.jar的包,该包在网上可以找到。

第一步,创建Excel对象。

HSSFWorkbook workbook = new HSSFWorkbook(); 

创建一个工作表。

HSSFSheet sheet = workbook.createSheet("日常收入报表"); 

创建合并单元格对象。第一个参数:起始行;第二个参数:结束行;第三个参数:起始列;第四个参数:结束列。

CellRangeAddress callRangeAddress = new CellRangeAddress(0,0,0,6); 

加载合并单元格对象。

sheet.addMergedRegion(callRangeAddress); 

设置单元格格式。

HSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//居中 

添加标题。

HSSFRow Row = sheet.createRow(0);//第一行 Row.setHeightInPoints(20);//设置行高 HSSFCell headCell = Row.createCell(0);//第一列 headCell.setCellValue("日常收入报表");//单元格内容 headCell.setCellStyle(cellStyle);//设置格式 

添加表头行。

HSSFRow hssfRow = sheet.createRow(1);//第二行 

添加表头内容。

headCell = hssfRow.createCell(0);//第一列 headCell.setCellValue("业务日期");//单元格内容 headCell.setCellStyle(cellStyle);//设置格式 

添加数据内容(查询出数据通过循环遍历添加)

List<DailyIncome> dailyincome = dailyincomeService.SelectDailyIncome(string, integer); for (int i = 0; i < dailyincome.size(); i++) { 	hssfRow = sheet.createRow((int) i + 2); 	DailyIncome DailyIncome = dailyincome.get(i); 	//创建单元格,并设置值 	HSSFCell cell = hssfRow.createCell(0); 	cell.setCellValue(DailyIncome.getDailyincomebusinessdate().toString()); 	cell.setCellStyle(cellStyle); } 

最后保存Excel文件

try { 	response.setHeader("Content-Disposition","attachment;filename=DailyIncome"); 	response.setContentType("application/octet-stream;charset=utf-8"); 	OutputStream outputStream = response.getOutputStream(); 	workbook.write(outputStream); 	outputStream.close(); } catch (Exception e) { 	e.printStackTrace(); } 

Exccel导出的数据如下图:

文章来源: https://blog.csdn.net/weixin_44547599/article/details/92574721
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!