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;
}
}複製程式碼