昨天写了一篇将Excel中的数据保存到数据库中的文档,今天续写一篇将数据库中的数据导出成Excel文件的
写的不好,也是最基础的,请多多指教
直接贴上代码:
1.还是一样先导入pom文件
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
2.将数据导出成Excel文件的Util类
/**
* 将数据导出成Excel文件
*
* @param sheetName sheet名称
* @param title 标题
* @param values 内容
* @param wb HSSFWorkbook对象
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values, HSSFWorkbook wb) {
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if (wb == null) {
wb = new HSSFWorkbook();
}
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
//设置单元格宽度自适应,在此基础上把宽度调至1.5倍
for (int i = 0; i < title.length; i++) {
sheet.autoSizeColumn(i, true);
sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 15 / 10);
}
// 声明列对象
HSSFCell cell = null;
// 创建标题
for (int i = 0; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
sheet.autoSizeColumn(i);
sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);
}
// 创建内容
for (int i = 0; i < values.length; i++) {
row = sheet.createRow(i + 1);
for (int j = 0; j < values[i].length; j++) {
// 将内容按顺序赋给对应的列对象
row.createCell(j).setCellValue(values[i][j]);
}
}
return wb;
}
3.控制层
/**
* 导出数据为Excel文件
* 下面注释的代码为直接响应到服务器的
* @param request
* @param response
* @return
*/
@GetMapping("/exportExcel")
public String exportExcel(HttpServletRequest request, HttpServletResponse response) {
List<TzJobSet> list = tzJobSetService.list();
String resultName ="";
String[] title = {"ID", "标题", "排序", "创建时间"};
// String filename = "jobSet.xls";
String sheetName = "职称设置表";
String[][] content = new String[list.size()][4];
try {
for (int i = 0; i < list.size(); i++) {
content[i][0] = String.valueOf(list.get(i).getId());
content[i][1] = list.get(i).getTitle();
content[i][2] = String.valueOf(list.get(i).getSortId());
content[i][3] = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(list.get(i).getAddTime());
}
} catch (Exception e) {
e.printStackTrace();
}
HSSFWorkbook wb = ImportExcel.getHSSFWorkbook(sheetName, title, content, null);
try {
String ctxPath = "D://upFiles";
String name = new SimpleDateFormat("ddHHmmss").format(new Date());
String fileName=name+"jobSet.xlsx";
String bizPath = "files";
String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
}
String savePath = file.getPath() + File.separator + fileName;
resultName = bizPath + File.separator + nowday+ File.separator + fileName;
if (resultName.contains("\\")) {
resultName = resultName.replace("\\", "/");
}
System.out.print(resultName);
System.out.print(savePath);
// 响应到客户端需要下面注释的代码
// this.setResponseHeader(response, filename);
// OutputStream os = response.getOutputStream(); //响应到服务器
OutputStream os = new FileOutputStream(savePath); // 保存到当前路径savePath
wb.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
return resultName;
}
下面的代码是向客户端发送响应流方法(个人喜欢将文件保存返回地址)
/**
* 向客户端发送响应流方法
*
* @param response
* @param fileName
*/
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
} catch (Exception ex) {
ex.printStackTrace();
}
}