SXSSFWorkbook使用——使用excel模板
生活随笔
收集整理的這篇文章主要介紹了
SXSSFWorkbook使用——使用excel模板
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
public class Hello {public static void main(String[] args) {// 1.導入excel模板String targetPath = rs.getSession().getServletContext().getRealPath("/excelModel/" + fileName + ".xlsx");// 2.創建一個workbook,對應一個Excel文件File fi = new File(targetPath);FileInputStream is = new FileInputStream(fi);XSSFWorkbook wb = new XSSFWorkbook(is);int lastRowNum = wb.getSheetAt(0).getLastRowNum();if (fileName.contains("橫向明細")) {wb.getSheetAt(0).getRow(3).getCell(0).setCellValue("分配期號:" + hxmxFpqh);}SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(wb, 1000);Sheet sheet = sxssfWorkbook.getSheetAt(0);// 開始填寫查找出來的數據writeExcel(list, sheet, lastRowNum);// 下載tkDownload2(sheetName, sxssfWorkbook, res);}public static void writeExcel(List<?> list, Sheet sheet, int lastRowNum)throws IOException, IllegalArgumentException,IllegalAccessException {Row row;for (int i = 0; i < list.size(); i++) {row = sheet.createRow((int) i + lastRowNum + 1);row.createCell(0).setCellValue(i + 1);Object tjb = list.get(i);Class class1 = (Class) tjb.getClass();Field[] fs = class1.getDeclaredFields();for (int j = 1; j < fs.length; j++) {Field f = fs[j];f.setAccessible(true);Object v = f.get(tjb);String type = f.getType().toString();if (v == null || v.toString() == "") {row.createCell(j).setCellValue("");} else {if (type.endsWith("Double") || type.endsWith("double")) {row.createCell(j).setCellValue(Double.parseDouble(v.toString()));} else if (type.endsWith("Integer") || type.endsWith("int")) {row.createCell(j).setCellValue(Double.parseDouble(v.toString()));} else if (type.endsWith("String")) {row.createCell(j).setCellValue(v.toString());}}}}}public static void tkDownload2(String sheetName, SXSSFWorkbook wb,HttpServletResponse res) throws IOException {String fileName = sheetName;ByteArrayOutputStream os = new ByteArrayOutputStream();wb.write(os);byte[] content = os.toByteArray();InputStream is = new ByteArrayInputStream(content);// 設置response參數,可以打開下載頁面res.reset();res.setContentType("application/vnd.ms-excel;charset=utf-8");res.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName + ".xlsx", "UTF-8"));// 設置文件名try (ServletOutputStream out = res.getOutputStream();BufferedInputStream bis = new BufferedInputStream(is);BufferedOutputStream bos = new BufferedOutputStream(out)) {byte[] buff = new byte[2048];int bytesRead;// Simple read/write loop.while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {bos.write(buff, 0, bytesRead);}} catch (Exception e) {//e.printStackTrace();logger.error("tkDownload failed |{}", () -> e.toString());logger.debug("failed {}", e);}}}
總結
以上是生活随笔為你收集整理的SXSSFWorkbook使用——使用excel模板的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++17(28)-Makefile(2
- 下一篇: javascript引擎V8精要(1)