From 26b7123ebccf218d17cf015566e0ad6b0bc3ea2c Mon Sep 17 00:00:00 2001 From: lxyer <237809796@qq.com> Date: Sun, 2 Dec 2018 14:03:46 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E5=96=84=E4=BB=A3=E7=A0=81=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 62 +-- src/com/lxyer/excel/poi/ExcelKit.java | 666 ++++++++++++------------ test/com/lxyer/excel/ExcelKitTest.java | 4 +- test/com/lxyer/excel/ExportKitTest.java | 19 +- 4 files changed, 359 insertions(+), 392 deletions(-) diff --git a/pom.xml b/pom.xml index 07af22b..ea9a234 100644 --- a/pom.xml +++ b/pom.xml @@ -5,9 +5,34 @@ 4.0.0 com.lxyer - jdk-demo - 1.0-SNAPSHOT + excel + 0.1.0 + jar + + + + + org.apache.poi + poi + 3.17 + + + org.apache.poi + poi-ooxml + 3.17 + + + + + junit + junit + 4.12 + test + + + + JExcel src test @@ -26,37 +51,4 @@ - - - - org.apache.poi - poi - 3.17 - - - org.apache.poi - poi-ooxml - 3.17 - - - - org.redkale - redkale - 1.9.3 - test - - - org.apache.tomcat - servlet-api - 6.0.37 - compile - - - junit - junit - 4.12 - test - - - \ No newline at end of file diff --git a/src/com/lxyer/excel/poi/ExcelKit.java b/src/com/lxyer/excel/poi/ExcelKit.java index 6650ffe..7b5765f 100644 --- a/src/com/lxyer/excel/poi/ExcelKit.java +++ b/src/com/lxyer/excel/poi/ExcelKit.java @@ -5,392 +5,366 @@ import org.apache.poi.poifs.filesystem.OfficeXmlFileException; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.io.OutputStream; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.*; /** - * 使用poi报表导出工具类 - * 把poi的一个调用接口抽出来,便于导出功能的管理 - * @author LiangXianYou lxy208@126.com - * @param - * - */ -public class ExcelKit { - - /** - * 导出list中map做载体的数据到excel
- * 参数说明:
- * list:存放了Map数据的集合
- * hdNames:表头列名
- * hds:对应表头的数据KEY
- * xlsName:导出文件名
- * @author LiangXianYou - * @date 2015-6-25 上午10:22:51 - */ - public static boolean exportByMap(List> list, String[] hdNames, String[] hds, String xlsName, HttpServletRequest request, HttpServletResponse response) throws Exception{ - - Workbook wb = new XSSFWorkbook(); //创建工作薄 - Sheet sheet = wb.createSheet(); //创建工作表 - sheet.autoSizeColumn(( short ) 0 ); //自适应宽度 - //写入表头---Excel的第一行数据 - Row nRow = sheet.createRow(0); //创建行 - for(int i=0;i boolean exportExcels(List> list,String xlsName, HttpServletRequest request, HttpServletResponse response) throws Exception{ - - Workbook wb = new XSSFWorkbook(); //创建工作薄 - for(int i=0;i map = list.get(i); - Sheet sheet = wb.createSheet(); //创建工作表 - String sheetName = (String) map.get("sheetName"); - wb.setSheetName(i, sheetName); - //写入表头---Excel的第一行数据 - Row nRow = sheet.createRow(0); //创建行 - String[] hdNames = (String[]) map.get("hdNames"); - for(int j=0;j data = (List) map.get("data"); - String[] hds = (String[]) map.get("hds"); - for(int j=0;j boolean exportExcel(List list, String[] hdNames, String[] hds, String xlsName, HttpServletRequest request, HttpServletResponse response) throws Exception{ - - Workbook wb = new XSSFWorkbook(); //创建工作薄 - Sheet sheet = wb.createSheet(); //创建工作表 - sheet.autoSizeColumn(( short ) 0 ); //自适应宽度 - //写入表头---Excel的第一行数据 - Row nRow = sheet.createRow(0); //创建行 - for(int i=0;i Workbook exportExcels(List> list) throws Exception { - //read excel head - public static Map readExcelHead(File file, String[] fields) throws IOException { - List list = readExcel(file, fields, 1, null); - return list.size() > 0 ? list.get(0) : new HashMap(); - } - //read excel head by sheetName - public static Map readExcelHead(File file, String[] fields, String sheetName) throws IOException { - List list = readExcel(file, fields, 1, sheetName); - return list.size() > 0 ? list.get(0) : new HashMap(); - } + Workbook wb = new XSSFWorkbook(); //创建工作薄 + for (int i = 0; i < list.size(); i++) { + Map map = list.get(i); + Sheet sheet = wb.createSheet(); //创建工作表 + String sheetName = (String) map.get("sheetName"); + wb.setSheetName(i, sheetName); + //写入表头---Excel的第一行数据 + Row nRow = sheet.createRow(0); //创建行 + String[] hdNames = (String[]) map.get("hdNames"); + for (int j = 0; j < hdNames.length; j++) { + Cell nCell = nRow.createCell(j); //创建单元格 + nCell.setCellValue(hdNames[j]); + } - //read excel sheet[0] - public static List readExcel(File file, String[] fields) throws IOException { - return readExcel(file, fields, -1, null); - } + //写入每一行数据---一条记录就是一行数据 + @SuppressWarnings("unchecked") + List data = (List) map.get("data"); + String[] hds = (String[]) map.get("hds"); + for (int j = 0; j < data.size(); j++) { + for (int k = 0; k < hds.length; k++) { + Object o = getFieldValue(data.get(j), hds[k]); //得到列的值 + data2Excel(sheet, o, j + 1, k); //将值写入Excel + } + } + } - //read excel sheet[0] no fields - public static List readExcel(File file) throws IOException { - return readExcel(file, null, -1, null); - } + return wb; + } - //read excel by sheetName - public static List readExcel(File file, String[] fields, String sheetName) throws IOException { - return readExcel(file, fields, -1, sheetName); - } + /** + * 参数说明: + * list:list数据集合 + * hdNames:表头需要显示的名称 + * hds:表头对应的对象属性名称,和 hdNames一一对应 + * xlsName:导出Excel的预定义名称 + * request: HttpServletRequest + * response:HttpServletResponse + * 通过数据构建Excel + * + * @throws Exception + * @author LiangXianYou + * @date 2015-3-13 上午11:00:30 + */ + public static Workbook exportExcel(List list, String[] hdNames, String[] hds) throws Exception { - //read excel by sheetName no fields - public static List readExcel(File file, String sheetName) throws IOException { - return readExcel(file, null, -1, sheetName); - } + Workbook wb = new XSSFWorkbook(); //创建工作薄 + Sheet sheet = wb.createSheet(); //创建工作表 + sheet.autoSizeColumn((short) 0); //自适应宽度 + //写入表头---Excel的第一行数据 + Row nRow = sheet.createRow(0); //创建行 + for (int i = 0; i < hdNames.length; i++) { + Cell nCell = nRow.createCell(i); //创建单元格 + nCell.setCellValue(hdNames[i]); + } - //read excel all sheet - public static Map> readExcelAll(File file, String[] fields) throws IOException { - return readExcelAll(file, fields, -1); - } + //写入每一行数据---一条记录就是一行数据 + for (int i = 0; i < list.size(); i++) { + for (int j = 0; j < hds.length; j++) { + Object o = getFieldValue(list.get(i), hds[j]); //得到列的值 + data2Excel(sheet, o, i + 1, j); //将值写入Excel + } + } + return wb; + } - //read all excel no fields - public static Map> readExcelAll(File file) throws IOException { - return readExcelAll(file, null, -1); - } - //read excel sheet[0] - private static List readExcel(File file, String[] fields, int lastRowNum, String sheetName) throws IOException { - Workbook wk; - try { - wk = new HSSFWorkbook(new FileInputStream(file));//if excel version 2007+ will throws OfficeXmlFileException - }catch (OfficeXmlFileException e){ - wk = new XSSFWorkbook(new FileInputStream(file)); - } - Sheet sheet = sheetName == null ? wk.getSheetAt(0) : wk.getSheet(sheetName); - if (sheet == null) throw new OfficeXmlFileException("sheet["+sheetName+"] can't find"); - return readExcel(sheet, fields, lastRowNum); - } + /** + * 通过泛型实例对象得到某一字段值 + * + * @author LiangXianYou + * @date 2015-3-13 上午10:53:32 + */ + private static Object getFieldValue(T t, String fieldName) throws Exception { + Object v; - /** - * read excel all sheet, - * can read excel 2007+ and 2007- - * @param file - * @param fields - * @param lastRowNum - * @return - * @throws IOException - */ - private static Map> readExcelAll(File file, String[] fields, int lastRowNum) throws IOException { - Workbook wk; - try { - wk = new HSSFWorkbook(new FileInputStream(file));//if excel version 2007+ will throws OfficeXmlFileException - }catch (OfficeXmlFileException e){ - wk = new XSSFWorkbook(new FileInputStream(file)); - } + if (t == null) { + v = null; + } else if (t instanceof Map) { + v = ((Map) t).get(fieldName); //得到列的值 + } else { + Field field = t.getClass().getDeclaredField(fieldName); + field.setAccessible(true); //暴力反射 + v = field.get(t); //得到字段数据的值 + } - Map> data = new LinkedHashMap<>(); - //reading all sheet - for (int i = 0; i < wk.getNumberOfSheets(); i++) { - Sheet sheet = wk.getSheetAt(i); - List maps = readExcel(sheet, fields, lastRowNum); + return v; + } - //move head - if (lastRowNum < 0 && maps.size() > 0){ - maps.remove(0); - } - data.put(sheet.getSheetName(), maps); - } - return data; - } + /** + * 将数据写到Excel中 + * + * @author LiangXianYou + * @date 2015-3-13 上午10:37:55 + */ + private static void data2Excel(Sheet sheet, Object o, Integer r, Integer c) { + //通过获得sheet中的某一列,有得到,没有创建 + Row nRow = sheet.getRow(r); + if (nRow == null) { + nRow = sheet.createRow(r); + } + Cell nCell = nRow.createCell(c); - /** - * read excel - * @author Lxyer 2016/8/1 10:32. - */ - private static List readExcel(Sheet sheet, String[] fields, int lastRowNum) throws OfficeXmlFileException { - if (fields == null || fields.length == 0){ - return readExcel(sheet, lastRowNum); - } + //根据不同类型进行转化,如有其它类型没有考虑周全的,使用发现的时候添加 + if (o instanceof Integer) nCell.setCellValue((Integer) o); + else if (o instanceof Double) nCell.setCellValue((Double) o); + else if (o instanceof Float) nCell.setCellValue((Float) o); + else if (o instanceof String) nCell.setCellValue((String) o); + else if (o instanceof Date) nCell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(o)); + else if (o instanceof Calendar) nCell.setCellValue((Calendar) o); + else if (o instanceof Boolean) nCell.setCellValue((Boolean) o); + else if (o == null) nCell.setCellValue(""); + else nCell.setCellValue(o + ""); + } - List list = new ArrayList<>(); - if (lastRowNum < 0 || lastRowNum > sheet.getLastRowNum()){ - lastRowNum = sheet.getLastRowNum(); - } + //======================= 读取excel =============================== - int t = 0; - r:for (int i=0; i<=lastRowNum; i++){ - Row row = sheet.getRow(i); - if (row == null) continue ; - short cellNum = row.getLastCellNum(); - //空跳过/连续三行为空结束 - if (isEmptyRow(row, fields.length)) { - if (t++ > 3) break; - continue ; - } + //read excel head + public static Map readExcelHead(File file, String[] fields) throws IOException { + List list = readExcel(file, fields, 1, null); + return list.size() > 0 ? list.get(0) : new HashMap(); + } - Map map = new HashMap(); - for (int j=0; j list = readExcel(file, fields, 1, sheetName); + return list.size() > 0 ? list.get(0) : new HashMap(); + } - if (cell.getCellTypeEnum() == CellType.NUMERIC){ - map.put(fields[j], (long)cell.getNumericCellValue()+""); - }else { - map.put(fields[j], cell.getStringCellValue()); - } - } - list.add(map); - } - return list; - } + //read excel sheet[0] + public static List readExcel(File file, String[] fields) throws IOException { + return readExcel(file, fields, -1, null); + } - /** - * - * @author Lxyer 2016/9/21 00:38. - */ - private static List readExcel(Sheet sheet, int lastRowNum) throws OfficeXmlFileException { - List list = new ArrayList<>(); - if (lastRowNum < 0 || lastRowNum > sheet.getLastRowNum()){ - lastRowNum = sheet.getLastRowNum(); - } + //read excel sheet[0] no fields + public static List readExcel(File file) throws IOException { + return readExcel(file, null, -1, null); + } - int t = 0; - r:for (int i=0; i<=lastRowNum; i++){ - Row row = sheet.getRow(i); - if (row == null) continue ; - short cellNum = row.getLastCellNum(); - //空跳过/连续三行为空结束 - if (isEmptyRow(row, 3)) { - if (t++ > 3) break; - continue ; - } + //read excel by sheetName + public static List readExcel(File file, String[] fields, String sheetName) throws IOException { + return readExcel(file, fields, -1, sheetName); + } - Map map = new HashMap(); - for (int j=0; j < cellNum; j++){ - String field = (char)((j/26 ==0? ' ' : 'a')+j/26) + "" +(char)('a'+j%26); - field = field.replace(" ",""); - Cell cell = row.getCell(j); - if (cell == null){ - map.put(field, ""); - continue; - } + //read excel by sheetName no fields + public static List readExcel(File file, String sheetName) throws IOException { + return readExcel(file, null, -1, sheetName); + } - if (cell.getCellTypeEnum() == CellType.NUMERIC){ - map.put(field, (long)cell.getNumericCellValue()+""); - }else { - map.put(field, cell.getStringCellValue()); - } - } - list.add(map); - } - return list; - } + //read excel all sheet + public static Map> readExcelAll(File file, String[] fields) throws IOException { + return readExcelAll(file, fields, -1); + } - //空跳过/连续三行为空结束 - private static boolean isEmptyRow(Row row, int len){ - for (int i = 0; i< row.getLastCellNum() && i < len; i++) { - Cell cell = row.getCell(i);//列 - if (cell != null){ - if (cell.getCellTypeEnum() != CellType.NUMERIC && cell.getStringCellValue() != null && !cell.getStringCellValue().isEmpty()){ - return false; - }else if (cell.getCellTypeEnum() == CellType.NUMERIC && cell.getNumericCellValue() != 0){ - return false; - } - } - } - return true; - } + //read all excel no fields + public static Map> readExcelAll(File file) throws IOException { + return readExcelAll(file, null, -1); + } - //get all sheet names - public static List getSheetNames(File file) throws IOException { - Workbook wk; - try { - wk = new HSSFWorkbook(new FileInputStream(file));//if excel version 2007+ will throws OfficeXmlFileException - }catch (OfficeXmlFileException e){ - wk = new XSSFWorkbook(new FileInputStream(file)); - } + //read excel sheet[0] + private static List readExcel(File file, String[] fields, int lastRowNum, String sheetName) throws IOException { + Workbook wk = getWorkbook(file); + Sheet sheet = sheetName == null ? wk.getSheetAt(0) : wk.getSheet(sheetName); + if (sheet == null) throw new OfficeXmlFileException("sheet[" + sheetName + "] can't findList"); - List sheetNames = new ArrayList<>(); - for (int i = 0; i < wk.getNumberOfSheets(); i++) { - sheetNames.add(wk.getSheetAt(i).getSheetName()); - } - return sheetNames; - } + if (lastRowNum < 0 || lastRowNum > sheet.getLastRowNum()) { + lastRowNum = sheet.getLastRowNum(); + } + return readExcel(sheet, fields, lastRowNum); + } + + /** + * read excel all sheet, + * can read excel 2007+ and 2007- + * + * @param file + * @param fields + * @param lastRowNum + * @return + * @throws IOException + */ + private static Map> readExcelAll(File file, String[] fields, int lastRowNum) throws IOException { + Workbook wk = getWorkbook(file); + + Map> data = new LinkedHashMap<>(); + //reading all sheet + for (int i = 0; i < wk.getNumberOfSheets(); i++) { + Sheet sheet = wk.getSheetAt(i); + List maps = readExcel(sheet, fields, lastRowNum); + + //move head + if (lastRowNum < 0 && maps.size() > 0) { + maps.remove(0); + } + data.put(sheet.getSheetName(), maps); + } + return data; + } + + /** + * read excel + * + * @author Lxyer 2016/8/1 10:32. + */ + private static List readExcel(Sheet sheet, String[] fields, int lastRowNum) throws OfficeXmlFileException { + if (lastRowNum < 0 || lastRowNum > sheet.getLastRowNum()) { + lastRowNum = sheet.getLastRowNum(); + } + + if (fields == null || fields.length == 0) { + return readExcel(sheet, lastRowNum); + } + + List list = new ArrayList<>(); + int t = 0; + r: + for (int i = 0; i <= lastRowNum; i++) { + Row row = sheet.getRow(i); + if (row == null) continue; + short cellNum = row.getLastCellNum(); + //空跳过/连续三行为空结束 + if (isEmptyRow(row, fields.length)) { + if (t++ > 3) break; + continue; + } + + Map map = new HashMap(); + for (int j = 0; j < cellNum && j < fields.length; j++) { + Cell cell = row.getCell(j); + if (cell == null) { + map.put(fields[j], ""); + continue; + } + + if (cell.getCellTypeEnum() == CellType.NUMERIC) { + map.put(fields[j], (long) cell.getNumericCellValue() + ""); + } else { + map.put(fields[j], cell.getStringCellValue()); + } + } + list.add(map); + } + return list; + } + + /** + * @author Lxyer 2016/9/21 00:38. + */ + private static List readExcel(Sheet sheet, int lastRowNum) throws OfficeXmlFileException { + List list = new ArrayList<>(); + if (lastRowNum < 0 || lastRowNum > sheet.getLastRowNum()) { + lastRowNum = sheet.getLastRowNum(); + } + + int t = 0; + r: + for (int i = 0; i <= lastRowNum; i++) { + Row row = sheet.getRow(i); + if (row == null) continue; + short cellNum = row.getLastCellNum(); + //空跳过/连续三行为空结束 + if (isEmptyRow(row, 3)) { + if (t++ > 3) break; + continue; + } + + Map map = new HashMap(); + for (int j = 0; j < cellNum; j++) { + String field = (char) ((j / 26 == 0 ? ' ' : 'a') + j / 26) + "" + (char) ('a' + j % 26); + field = field.replace(" ", ""); + Cell cell = row.getCell(j); + if (cell == null) { + map.put(field, ""); + continue; + } + + if (cell.getCellTypeEnum() == CellType.NUMERIC) { + map.put(field, (long) cell.getNumericCellValue() + ""); + } else { + map.put(field, cell.getStringCellValue()); + } + } + list.add(map); + } + return list; + } + + //空跳过/连续三行为空结束 + private static boolean isEmptyRow(Row row, int len) { + for (int i = 0; i < row.getLastCellNum() && i < len; i++) { + Cell cell = row.getCell(i);//列 + if (cell != null) { + if (cell.getCellTypeEnum() != CellType.NUMERIC && cell.getStringCellValue() != null && !cell.getStringCellValue().isEmpty()) { + return false; + } else if (cell.getCellTypeEnum() == CellType.NUMERIC && cell.getNumericCellValue() != 0) { + return false; + } + } + } + return true; + } + + //get all sheet names + public static List getSheetNames(File file) throws IOException { + Workbook wk = getWorkbook(file); + List sheetNames = new ArrayList<>(); + for (int i = 0; i < wk.getNumberOfSheets(); i++) { + sheetNames.add(wk.getSheetAt(i).getSheetName()); + } + return sheetNames; + } + + private static Workbook getWorkbook(File file) throws IOException { + Workbook wk; + try { + wk = new HSSFWorkbook(new FileInputStream(file));//if excel version 2007+ will throws OfficeXmlFileException + } catch (OfficeXmlFileException e) { + wk = new XSSFWorkbook(new FileInputStream(file)); + } + + return wk; + } } diff --git a/test/com/lxyer/excel/ExcelKitTest.java b/test/com/lxyer/excel/ExcelKitTest.java index c9ad151..5bd4112 100644 --- a/test/com/lxyer/excel/ExcelKitTest.java +++ b/test/com/lxyer/excel/ExcelKitTest.java @@ -14,7 +14,7 @@ import java.util.Map; public class ExcelKitTest { //read excel by fields - @Test + //@Test public void readTest() throws IOException { /*String sql1 = "select a, b, c from Sheet1"; String sql2 = "select a, b, c from Sheet1 where a=1 order by b"; @@ -33,7 +33,7 @@ public class ExcelKitTest { } //read excel no fields - @Test + //@Test public void readTest2() throws IOException { List list = ExcelKit.readExcel(new File("res/test.xlsx")); diff --git a/test/com/lxyer/excel/ExportKitTest.java b/test/com/lxyer/excel/ExportKitTest.java index 26e4758..5a1c11e 100644 --- a/test/com/lxyer/excel/ExportKitTest.java +++ b/test/com/lxyer/excel/ExportKitTest.java @@ -1,13 +1,10 @@ package com.lxyer.excel; -import org.junit.Test; -import org.redkale.net.http.HttpResponse; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.*; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; import java.util.*; -import java.util.concurrent.CountDownLatch; import java.util.function.BiFunction; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @@ -25,7 +22,7 @@ import java.util.zip.ZipOutputStream; public class ExportKitTest { //1、导出List示例 - @Test + //@Test public void exportBean(){ Map heads = new LinkedHashMap(); heads.put("姓名", "name"); @@ -52,7 +49,7 @@ public class ExportKitTest { } //2、导出List 示例 - @Test + //@Test public void exportMapToZip(){ Map heads = new LinkedHashMap(); @@ -101,6 +98,7 @@ public class ExportKitTest { * @return * @throws IOException */ + /* public boolean exportExcel(Map head, List rows, HttpServletRequest request, HttpServletResponse response, String xlsName, BiFunction fun) throws IOException { if(request.getHeader("user-agent") != null && request.getHeader("user-agent").indexOf("MSIE") != -1) { xlsName = java.net.URLEncoder.encode(xlsName,"utf-8") + ".xls"; @@ -120,6 +118,7 @@ public class ExportKitTest { os.write(ExcelExportKit.exportExcel(head, rows, fun).toString().getBytes()); return true; } + */ /** * 4、导出压缩的excel示例 @@ -156,6 +155,7 @@ public class ExportKitTest { * @return * @throws IOException */ + /* public static void exportExcel(Map head, List rows, HttpResponse response, String xlsName, BiFunction fun) throws IOException { xlsName = new String(xlsName.getBytes("utf-8"),"iso-8859-1")+ ".xls"; @@ -165,4 +165,5 @@ public class ExportKitTest { StringBuilder buf = ExcelExportKit.exportExcel(head, rows, fun); response.finish(buf.toString().getBytes()); } + */ }