資料匯出到Excel文件
阿新 • • 發佈:2021-01-12
技術標籤:2021年1月javaexceljavaspring
資料匯出到Excel文件技術集合
在專案開發中難免會碰到將前端表格匯出到Excel文件中,今天就對最近使用的匯出技術做一個總結,方便以後開發的時候查詢和使用。
1、匯出前端表格中選定行的內容
1、 Controller層程式碼
@RequestMapping(value = "/exports", method = RequestMethod.POST)
public void exports(@RequestBody String item,HttpServletResponse resp) throws UnsupportedEncodingException {
String keyWord = URLDecoder.decode(item, "UTF-8");
JSONArray jSONArray = JSONArray.parseArray(keyWord.substring(5, keyWord.length()));
List<Test> list = JSONObject.parseArray(jSONArray.toJSONString(), Test.class);
// 事先將設定好格式的表格匯入專案中
String fileName = "測試報表.xls";
String templatePath = "templates/" + fileName;
try {
ExportExcelUtil.exportTestExcels(list, fileName, templatePath, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
2 、實現方法程式碼:
/**
* 將資料匯出成EXCEL檔案的方法
* @Title: exportEntityExcel
* @Description: TODO(這裡用一句話描述這個方法的作用)
* @param lists 查詢結果集
* @param fileName 模板檔名
* @param templatePath 模板路徑名
* @Date 2016年2月15日 下午3:06:17
*/
public static void exportTestExcels(List<Test> list, String fileName, String templatePath, HttpServletResponse re) throws Exception {
// 告訴瀏覽器用什麼軟體可以開啟此檔案
re.setHeader("content-Type", "selfdefinition");
// 下載檔案的預設名稱
re.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
exportTrainDataExcels(list, templatePath, re.getOutputStream());
}
private static void exportTestExcels(List<Test> list, String templatePath, OutputStream out) {
// 宣告一個工作薄
Workbook wb = null;
Cell currentCell= null;
try {
wb = getExcelWorkbook(templatePath);
if (wb == null) {
return;
}
// ******************讀取工作區,獲取表字段定義資訊*******************
// 獲得該工作區的第一個sheet
Sheet sheet = wb.getSheetAt(0);
int i = 0;
int j = list.size();
while (i < j) {
Test entity = list.get(i);
setCellValues(sheet, i+1, 0, entity.getName());
setCellValues(sheet, i+1, 1, entity.getAge());
setCellValues(sheet, i+1, 2, entity.getSex());
i++;
// 列寬自適應
int curColWidth = sheet.getColumnWidth(i) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
Row currentRow;
// 當前行未被使用過
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(i) != null) {
currentCell = currentRow.getCell(i);
if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (curColWidth < length) {
curColWidth = length;
}
}
}
}
sheet.setColumnWidth(i, curColWidth * 250);
}
// 寫入
wb.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、從後臺匯出
1、controller層
@RequestMapping(value = "/exportsAll", method = RequestMethod.POST)
public void orderExcelExport(@RequestBody String item,HttpServletResponse resp) throws UnsupportedEncodingException {
String keyWord = URLDecoder.decode(item, "UTF-8");
keyWord=keyWord.replace("item", "").replace("=", "");
Test parseObject = JSONObject.parseObject(keyWord, Test.class);
List<Test> list = testService.selectAll(parseObject);
String fileName = "船舶匯出報表.ftl";
Map<String, Object> listMap = new HashMap<String, Object>();
listMap.put("findList", list);
try {
ExportExcelUtil.writeExcelOneSheet("templates" , fileName, "船舶匯出報表", "船舶匯出報表", resp, listMap);
} catch (Exception e) {
e.printStackTrace();
}
}
2、方法實現程式碼
/**
* 寫入單個Sheet的Excel
* @param templatePrefix 模板所在的路徑
* @param tempName 模板名稱
* @param excelName 生成的excel名稱不用加字尾
* @param sheetName 單個sheet名稱
* @param listMap 填充資料列表
* @param <T> 填充物件泛型
* @throws FileNotFoundException
* @throws ClassNotFoundException
*/
public static <T> void writeExcelOneSheet(String templatePrefix, String tempName , String excelName , String sheetName, HttpServletResponse response,Map<String, Object> listMap){
long startTimne = System.currentTimeMillis();
Template dateTmp = null;
Writer fw = null;
try {
// 此處需要給你個版本資訊,Configuration cfg = new Configuration();這個方法已經過時了
Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
// **********初始化引數**********
String url = ExportExcelUtil.class.getClassLoader().getResource(templatePrefix).getPath();
File tempFoldFile = new File(url);
if (!tempFoldFile.exists()) {
tempFoldFile.mkdirs();
}
cfg.setDirectoryForTemplateLoading(tempFoldFile);
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateUpdateDelay(0);
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// **********獲取freemaker模板**********
dateTmp = cfg.getTemplate(tempName,"utf-8");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;fileName="+new String(excelName.getBytes("gb2312"), "8859_1") + ".xls");
// **********生成輸出流**********
fw = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
// **********資料寫入模板**********
//Map<String, Object> listMap = new HashMap<String, Object>();
//listMap.put("findList", findList);
dateTmp.process(listMap, fw);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fw.close();
// 關閉檔案輸入輸出流
} catch (IOException e) {
e.printStackTrace();
}
}
long endTime = System.currentTimeMillis();
System.out.println("用時="+((endTime-startTimne)/1000)+"秒");
}
/**
* 將一個list均分成n個list,主要通過偏移量來實現的
* @param source
* @return
*/
public static <T> List<List<T>> averageAssignList(List<T> source, int n) {
List<List<T>> result = new ArrayList<List<T>>();
int remaider = source.size() % n; //(先計算出餘數)
int number = source.size() / n; //然後是商
int offset = 0;//偏移量
for (int i = 0; i < n; i++) {
List<T> value = null;
if (remaider > 0) {
value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
remaider--;
offset++;
} else {
value = source.subList(i * number + offset, (i + 1) * number + offset);
}
result.add(value);
}
return result;
}