将数据库中数据导出为excel表格

时间:2021-05-17 08:51:01
public class Excel {

    private static Logger logger = LoggerFactory.getLogger(Excel.class);

    /**
* 导出项目列表
*
* @param jsonArray
* @param request
* @param response
* @return
*/
public static Result createCloudServerXls(JSONArray jsonArray, HttpServletRequest request, HttpServletResponse response) {
try {
// 创建HSSFWorkbook
String sheetName = "报表导出";
//表头,根据自己需求更改
String[] cellTitle = new String[]{"学号","姓名","年龄","班级"};
String[][] rows = null;
List<Student> list = JSONArray.parseArray(jsonArray.toJSONString(), Student.class);
if (!ListTool.isEmpty(list)) {
rows = new String[list.size()][4];
for (int i = 0; i < list.size(); i++) {
Student student = list.get(i);
rows[i][0] = student.getSno();
rows[i][1] = student.getName();
rows[i][2] = student.getAge();
rows[i][3] = student.getGrade()
}
} else {
rows = new String[0][4];
}
HSSFWorkbook workbook = getHSSFWorkbook(sheetName, cellTitle, rows, null);
// 下载表格到浏览器
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");
String fileName = sheetName + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ".xls";
final String userAgent = request.getHeader("user-agent").toLowerCase();
if (userAgent.contains("trident") || userAgent.contains("edge")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
}
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
OutputStream os = response.getOutputStream();
workbook.write(os);
os.flush();
os.close();
} catch (Exception e) {
logger.error("生成文档失败", e);
return new Result(false, "发生异常生成文档失败");
}
return new Result(true, "生成文档成功");
} /**
* 导出Excel
*
* @param sheetName sheet名称
* @param title 标题
* @param values 内容
* @param wb HSSFWorkbook对象
* @return
*/
private 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); // 创建一个居中格式
// 声明列对象
HSSFCell cell = null;
// 创建标题
for (int i = 0; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
// 创建内容
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;
}
}