excel超过java 65535 条数据 poi SXSSFWorkbook

package aaa.utils.scanner.excel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import next.entity.Option;
/**
 * 
 * 大数据导出Excel工具类
 * @author: wqq
 * @date:2018年9月14日
 */
public class ExcelExport {
    /** 日期格式 yyyy-MM-dd*/
    private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    /**
     * 单元格映射
     */
    public static class CellMap {
        private String title;// 标题
        private String property;// 属性

        public CellMap(String title, String property) {
            this.title = title;
            this.property = property;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getProperty() {
            return property;
        }

        public void setProperty(String property) {
            this.property = property;
        }

    }
    /**
     * 导出数据兼容以前的
     * @param title
     * @param headMap
     * @param ja
     * @param response
     * @throws Exception
     */
    public static void downloadExcelFile(String title, Map<String, String> headMap,List<?> dataList, HttpServletResponse response) throws Exception{
        parseDownloadExcelFile(title, headMap,dataList,response);
    }
    /**
     * 以 SXSSF 导出2007(增强版)
     * <功能详细描述>
     * @param response
     * @param excelName
     * @param cellMapList
     * @param dataList
     * @param foot
     * @throws Exception
     */
    public static void exportExcel_2007_SXSSF(HttpServletResponse response,String excelName,List<CellMap> cellMapList,List<?> dataList,List<HashMap<String, Object>> foot) throws Exception{
        createExcel(response, excelName, cellMapList,dataList,foot);
    }
    /**
     * 以 SXSSF 导出2007  无页脚
     * @param response
     * @param excelName
     * @param cellMapList
     * @param dataList
     * @throws Exception
     */
    public static void exportExcel_2007_SXSSF(HttpServletResponse response,String excelName,List<CellMap> cellMapList,List<?> dataList) throws Exception{
        createExcel(response, excelName, cellMapList,dataList,null);
    }
    public static void parseDownloadExcelFile(String title, Map<String, String> headMap,List<?> dataList,HttpServletResponse response) throws Exception{
        List<CellMap> cellMapList=new ArrayList<CellMap>();
        for(String key:headMap.keySet()){
            CellMap CellMap=new CellMap(headMap.get(key),key);
            cellMapList.add(CellMap);
        }
        createExcel(response, title, cellMapList,dataList,null);
    }
    /**
     * 导出Excel
     * @param cellMapList 单元格映射列表
     * @param dataList 数据列表
     * @param rowAccessWindowSize 内存中缓存记录数
     * @param out 输出流
     * @throws Exception
     */
    public static void exportSXSSFExcel(String sheetName, List<CellMap> cellMapList, List<?> dataList, int rowAccessWindowSize, OutputStream out) throws Exception {
        @SuppressWarnings("resource")
        SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize);
        Sheet sheet = workbook.createSheet(sheetName);
        Row row = null;
        Cell cell = null;
        if (cellMapList == null || cellMapList.size() <= 0) {
            throw new Exception("cellMapList不能为空或小于等于0");
        }
        int rowIndex = 0;
        // 标题
        Font titleFont = workbook.createFont();
        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        CellStyle titleCellStyle = workbook.createCellStyle();
        titleCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        titleCellStyle.setFont(titleFont);
        row = sheet.createRow(rowIndex++);
        int cellSize = cellMapList.size();
        for (int i = 0; i < cellSize; i++) {
            CellMap cellMap = cellMapList.get(i);
            String title = cellMap.getTitle();
            cell = row.createCell(i);
            cell.setCellStyle(titleCellStyle);
            cell.setCellValue(title);
            if (title != null) {
                sheet.setColumnWidth(i, title.getBytes().length * 2 * 172);
            }
        }
        // 数据
        CellStyle dataCellStyle = workbook.createCellStyle();
        dataCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        int rowSize = (dataList == null) ? 0 : dataList.size();
        for (int i = rowIndex; i < rowSize + rowIndex; i++) {
            Object obj = dataList.get(i - rowIndex);
            row = sheet.createRow(i);
            for (int j = 0; j < cellSize; j++) {
                CellMap cellMap = cellMapList.get(j);
                cell = row.createCell(j);
                cell.setCellStyle(dataCellStyle);
                String property = cellMap.getProperty();
                if(property.equals("rowNumber") || StringUtils.isEmpty(property)){
                    cell.setCellValue(i);
                }else{
                    String propertyValue = getPropertyValue(obj, property);
                    cell.setCellValue(propertyValue);
                    if (propertyValue != null) {
                        int columnWidth = sheet.getColumnWidth(j);
                        int propertyValueLength = propertyValue.getBytes().length * 2 * 172;
                        if (columnWidth < propertyValueLength) {
                            sheet.setColumnWidth(j, propertyValueLength);
                        }
                    }
                }

            }
        }
        workbook.write(out);
    }


    /**
     * 导出Excel
     * @param cellMapList 单元格映射列表
     * @param dataList 数据列表
     * @param rowAccessWindowSize 内存中缓存记录数
     * @param out 输出流
     * @throws Exception
     */
    public static void exportSXSSFExcelFromMapData(String sheetName, List<CellMap> cellMapList, List<Map<String,String>> dataList, int rowAccessWindowSize, OutputStream out) throws Exception {
        @SuppressWarnings("resource")
        SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize);
        Sheet sheet = workbook.createSheet(sheetName);
        Row row = null;
        Cell cell = null;
        if (cellMapList == null || cellMapList.size() <= 0) {
            throw new Exception("cellMapList不能为空或小于等于0");
        }
        int rowIndex = 0;
        // 标题
        Font titleFont = workbook.createFont();
        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        CellStyle titleCellStyle = workbook.createCellStyle();
        titleCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        titleCellStyle.setFont(titleFont);
        row = sheet.createRow(rowIndex++);
        int cellSize = cellMapList.size();
        for (int i = 0; i < cellSize; i++) {
            CellMap cellMap = cellMapList.get(i);
            String title = cellMap.getTitle();
            cell = row.createCell(i);
            cell.setCellStyle(titleCellStyle);
            cell.setCellValue(title);
            if (title != null) {
                sheet.setColumnWidth(i, title.getBytes().length * 2 * 172);
            }
        }
        // 数据
        CellStyle dataCellStyle = workbook.createCellStyle();
        dataCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        int rowSize = (dataList == null) ? 0 : dataList.size();
        for (int i = rowIndex; i < rowSize + rowIndex; i++) {
            Map<String,String> obj = dataList.get(i - rowIndex);
            row = sheet.createRow(i);
            for (int j = 0; j < cellSize; j++) {
                CellMap cellMap = cellMapList.get(j);
                cell = row.createCell(j);
                cell.setCellStyle(dataCellStyle);
                String property = cellMap.getProperty();
                if(property.equals("rowNumber") || StringUtils.isEmpty(property)){
                    cell.setCellValue(i);
                }else{
//                  String propertyValue = getPropertyValue(obj, property);
                    String propertyValue = obj.get(property);
                    cell.setCellValue(propertyValue);
                    if (propertyValue != null) {
                        int columnWidth = sheet.getColumnWidth(j);
                        int propertyValueLength = propertyValue.getBytes().length * 2 * 172;
                        if (columnWidth < propertyValueLength) {
                            sheet.setColumnWidth(j, propertyValueLength);
                        }
                    }
                }

            }
        }
        workbook.write(out);
    }

    /**
     * 获取属性值
     * @param obj
     * @param property
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    private static String getPropertyValue(Object obj, String property) throws Exception {
        if (obj instanceof Map)
        {
            Object val = ((Map<String,Object>)obj).get(StringUtils.upperCase(property));
            if (val==null)
            {
                return "";
            }
            return val.toString();
        }
        Object result = null;
        String str = "";
        Class<?> clazz = obj.getClass();
        if (property == null || "".equals(property)) {
            return "";
        }
        Method readMethod = clazz.getMethod("get" + property.substring(0, 1).toUpperCase() + property.substring(1));
        if (readMethod != null) {
            result = readMethod.invoke(obj);
        }
        if (result != null) {
            if (result.getClass() == Date.class) {
                str = dateFormat.format(result);
            } else {
                str = result.toString();
            }
        } else {
            str = "";
        }
        return str;
    }


    public static void main(String[] args) {
         List<CellMap> cellMapList = new ArrayList<CellMap>();
         cellMapList.add(new CellMap("单元格1", "index"));
//         cellMapList.add(new CellMap("单元格21111111111", "cell2"));
//         cellMapList.add(new CellMap("单元格3", "a"));

         List<Option> list = new ArrayList<Option>();
         Option Option=new Option();
         Option.setIndex("2");
         for(int i=0;i<100000;i++) {
            list.add(Option);
         }
         list.add(Option);

         try {
             ExcelExport.exportSXSSFExcel("昂",cellMapList, list, 1000, new FileOutputStream(new File("C:\\Users\\dap\\Desktop\\新建文件夹\\test.xlsx")));
         } catch (Exception e) {
             e.printStackTrace();
         }
    }

    /**
     * 
     * 填充excel数据
     * <功能详细描述>
     * @param dataCellStyle
     * @param cellSize
     * @param sheet
     * @param rowIndex
     * @param workbook
     * @param response
     * @param excelName
     * @param cellMapList
     * @param dataList
     * @return
     * @throws Exception
     * @see [类、类#方法、类#成员]
     */
    public static int fillExcel_2007_SXSSF(CellStyle dataCellStyle,int cellSize,Sheet sheet,int rowIndex,SXSSFWorkbook workbook,HttpServletResponse response,String excelName, List<CellMap> cellMapList, List<?> dataList) throws Exception{
        Row row = null;
        Cell cell = null;
        int rowSize = (dataList == null) ? 0 : dataList.size();
        for (int i = rowIndex; i < rowSize + rowIndex; i++) {
            Object obj = dataList.get(i - rowIndex);
            row = sheet.createRow(i);
            for (int j = 0; j < cellSize; j++) {
                CellMap cellMap = cellMapList.get(j);
                cell = row.createCell(j);
                cell.setCellStyle(dataCellStyle);
                String property = cellMap.getProperty();
                if(property.equals("rowNumber") || StringUtils.isEmpty(property)){
                    cell.setCellValue(i);
                }else{
                    String propertyValue = getPropertyValue(obj, property);
                    cell.setCellValue(propertyValue);
                    if (propertyValue != null) {
                        int columnWidth = sheet.getColumnWidth(j);
                        int propertyValueLength = propertyValue.getBytes().length * 2 * 172;
                        if (columnWidth < propertyValueLength) {
//                            sheet.setColumnWidth(j, propertyValueLength);
                        }
                    }
                }
            }
        }
        return rowSize + rowIndex;
    }
    /**
     * 创建excel
     * @param response
     * @param excelName
     * @param cellMapList
     * @param dataList
     * @param footers
     * @throws Exception
     */
    public static void createExcel(HttpServletResponse response,String excelName, List<CellMap> cellMapList,List<?> dataList,List<HashMap<String, Object>> footers) throws Exception{
        //参数校验
        if (response==null||CollectionUtils.isEmpty(cellMapList))
        {
            throw new Exception("cellMapList不能为空或小于等于0");
        }
        if (StringUtils.isBlank(excelName))
        {
            excelName = UUID.randomUUID().toString();
        }
        @SuppressWarnings("resource")
        SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
        workbook.setCompressTempFiles(true);
        Sheet sheet = workbook.createSheet();
        Row row = null;
        Cell cell = null;
        int rowIndex = 0;
        // header 标题
        Font titleFont = workbook.createFont();
        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        CellStyle titleCellStyle = workbook.createCellStyle();
        titleCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        titleCellStyle.setFont(titleFont);
        row = sheet.createRow(rowIndex++);
        // 数据列数
        int cellSize = cellMapList.size();
        for (int i = 0; i < cellSize; i++) {
            CellMap cellMap = cellMapList.get(i);
            String title = cellMap.getTitle();
            cell = row.createCell(i);
            cell.setCellStyle(titleCellStyle);
            cell.setCellValue(title);
            if (title != null) {
                sheet.setColumnWidth(i, title.getBytes().length * 2 * 234);
            }
        }
        CellStyle dataCellStyle = workbook.createCellStyle();
        dataCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        int rowSize = (dataList == null) ? 0 : dataList.size();
        for (int i = rowIndex; i < rowSize + rowIndex; i++) {
            Object obj = dataList.get(i - rowIndex);
            row = sheet.createRow(i);
            for (int j = 0; j < cellSize; j++) {
                CellMap cellMap = cellMapList.get(j);
                cell = row.createCell(j);
                cell.setCellStyle(dataCellStyle);
                String property = cellMap.getProperty();
                if(property.equals("rowNumber") || StringUtils.isEmpty(property)){
                    cell.setCellValue(i);
                }else{
                    String propertyValue = getPropertyValue(obj, property);
                    cell.setCellValue(propertyValue);
                    if (propertyValue != null) {
                        int columnWidth = sheet.getColumnWidth(j);
                        int propertyValueLength = propertyValue.getBytes().length * 2 * 172;
                        if (columnWidth < propertyValueLength) {
                            sheet.setColumnWidth(j, propertyValueLength);
                        }
                    }
                }

            }
        }
      //footer 尾部
//        if (CollectionUtils.isNotEmpty(footers))
//        {
//          //footers数据样式
//            CellStyle dataCellStyle = workbook.createCellStyle();
//            dataCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//            rowIndex=fillExcel_2007_SXSSF(dataCellStyle,cellSize,sheet, rowIndex, workbook, response, excelName, cellMapList, footers);
//        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); 
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((excelName + ".xlsx").getBytes(), "iso-8859-1"));
        OutputStream out = response.getOutputStream();
        workbook.write(out);
        out.close();
        workbook.dispose();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: poi sxssfworkbook是Apache POI库中的一种工具,用于读取Excel文件。它特别适用于需要处理大型Excel文件的情况,因为它可以在内存中使用较少的资源来处理文件。 要使用sxssfworkbook读取Excel,首先需要导入Apache POI库。然后,可以通过创建一个sxssfworkbook对象来打开要读取的Excel文件。例如: ``` SXSSFWorkbook workbook = new SXSSFWorkbook(new FileInputStream("文件路径/文件名.xlsx")); ``` 读取工作表中的数据,可以通过遍历工作表中的行和列来实现。例如,假设要读取第一个工作表中的所有数据: ``` Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表 Iterator<Row> rowIterator = sheet.iterator(); // 遍历工作表中的行 while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); // 遍历行中的单元格 while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); String cellValue = cell.getStringCellValue(); // 获取单元格的值 System.out.println(cellValue); } } ``` 在处理完Excel文件后,应该关闭Workbook对象以释放资源。例如: ``` workbook.close(); ``` 通过使用poi sxssfworkbook读取Excel文件,可以方便地获取并处理工作表中的数据,使得 Excel 文件的读取和操作更加高效和灵活。 ### 回答2: poi sxssfworkbook是Apache POI框架中的一个类,用于读取Excel文件。它是SXSSFWorkbook的一种变体,具有更高的写入性能和低内存占用。 使用SXSSFWorkbook读取Excel的过程如下: 1. 导入Apache POI的依赖包,并创建工作簿对象: SXSSFWorkbook workbook = new SXSSFWorkbook(); 2. 创建工作表对象: SXSSFSheet sheet = workbook.createSheet("Sheet1"); 3. 读取Excel文件中的数据,可以使用循环遍历的方式逐行读取: for (Row row : sheet) { for (Cell cell : row) { // 获取单元格值 String cellValue = cell.getStringCellValue(); // 进行相关操作 } } 4. 关闭工作簿对象: workbook.close(); SXSSFWorkbook的优势在于可以处理大型Excel文件,节省内存资源。它使用了一种基于磁盘临时存储的机制,将数据缓存在磁盘上,而不是全部加载到内存中。这样可以减少内存占用,提高程序的性能和处理能力。 总结来说,使用poi sxssfworkbook读取Excel文件的过程较为简单,只需导入相关依赖包,创建工作簿和工作表对象,然后逐行读取数据。通过SXSSFWorkbook的特性,能够高效地处理大型Excel文件,实现对Excel数据的读取操作。 ### 回答3: Poi sxssfworkbook是Apache POI库中的一个类,它用于读取和处理大型的Excel文件(.xlsx格式)。下面是关于使用poi sxssfworkbook读取excel的说明。 1. 首先,需要在项目中导入Apache POI库的相关依赖,可以在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 导入必要的类: ```java import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; ``` 3. 创建一个SXSSFWorkbook对象: ```java SXSSFWorkbook workbook = new SXSSFWorkbook(); ``` 4. 获取要读取的Excel文件: ```java FileInputStream file = new FileInputStream(new File("path/to/excel/file.xlsx")); ``` 5. 创建一个XSSFWorkbook对象,用于处理工作表和行: ```java XSSFWorkbook workbook = new XSSFWorkbook(file); ``` 6. 获取第一个工作表: ```java XSSFSheet sheet = workbook.getSheetAt(0); ``` 7. 迭代读取每一行: ```java Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { XSSFRow row = (XSSFRow) rowIterator.next(); // 迭代读取每一列 Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { XSSFCell cell = (XSSFCell) cellIterator.next(); // 获取单元格的值 String cellValue = cell.getStringCellValue(); // 处理单元格的值 // ... } } ``` 8. 关闭工作簿和文件流: ```java workbook.close(); file.close(); ``` 通过上述步骤,就可以使用poi sxssfworkbook读取Excel文件中的数据了。请确保在使用poi sxssfworkbook之前,已经正确导入了Apache POI库的相关依赖。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值