Java导出Excel表格
导出Excel表格需要一个poi-3.9.jar的包,poi-3.9.jar百度云下载链接,提取码:petw。
第一步,创建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导出的数据如下图: