package com.tebon.ams.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.util.SAXHelper;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFComment;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: ${description}
 * @author: dfz
 * @create: 2018-12-14
 **/
@Slf4j
public class XLSX2CSV {
    /**
     * Uses the XSSF Event SAX helpers to do most of the work
     * of parsing the Sheet XML, and outputs the contents
     * as a (basic) CSV.
     */
    private List<String[]> rows = new ArrayList<String[]>();

private final OPCPackage xlsxPackage;

/**
     * Number of columns to read starting with leftmost
     */
    private int[] minColumns;

/**
     * Destination for data
     */
    private class SheetToCSV implements SheetContentsHandler {
        private String[] record;
        private int minColumns;
        private int thisColumn = 0;

public SheetToCSV(int minColumns) {
            super();
            this.minColumns = minColumns;
        }

@Override
        public void startRow(int rowNum) {
            record = new String[this.minColumns];
            // System.out.println("################################:"+rowNum);
        }

@Override
        public void endRow(int rowNum) {
            thisColumn = 0;
            if (!ObjectUtil.isEmpty(this.record) && !ObjectUtil.isEmpty(this.record[0])) {
                rows.add(this.record);
            }
            //一行结束要把此属性置""
            preXy = "";
            //System.out.println("**********************************");

}

//前一个单元格的xy
        private String preXy = "";
        //当前单元格的xy
        private String currXy = "";
        //前一个单元格的x
        private String preX = "";
        //当前单元格的x
        private String currX = "";
        //两个不为空的单元格之间隔了多少个空的单元格
        private int flag = 0;

@Override
        public void cell(String cellReference, String formattedValue, XSSFComment comment) {

//与判断空单元格有关
            if ("".equals(preXy)) {
                preXy = cellReference;
            }
            currXy = cellReference;
            preX = preXy.replaceAll("\\d", "").trim();
            currX = currXy.replaceAll("\\d", "").trim();
            int preAscii = 0;
            int curAscii = 0;
            preAscii = excelColStrToNum(preX, preX.length());
            curAscii = excelColStrToNum(currX, currX.length());
            flag = curAscii - preAscii;
            if (flag != 0 && flag != 1 && flag > 0) {
                //isSkipCeil = true;
                for (int i = 0; i < (flag - 1); i++) {
                    //appStr = appStr + ",";
                    record[thisColumn] = null;
                    thisColumn++;
                }
            }
            preXy = cellReference;
            if (thisColumn < this.minColumns)
                record[thisColumn] = formattedValue.trim();
            thisColumn++;

}

@Override
        public void headerFooter(String text, boolean isHeader, String tagName) {
            // Skip, no headers or footers in CSV
        }

}

/**
     * Creates a new XLSX -> CSV converter
     *
     * @param pkg        The XLSX package to process
     * @param minColumns The minimum number of columns to output, or -1 for no minimum
     */
    public XLSX2CSV(OPCPackage pkg, int... minColumns) {
        this.xlsxPackage = pkg;
        this.minColumns = minColumns;
    }

/**
     * Parses and shows the content of one sheet
     * using the specified styles and shared-strings tables.
     *
     * @param styles
     * @param strings
     * @param sheetInputStream
     */
    public void processSheet(StylesTable styles, ReadOnlySharedStringsTable strings, SheetContentsHandler sheetHandler, InputStream sheetInputStream)
            throws IOException, ParserConfigurationException, SAXException {
        DataFormatter formatter = new DataFormatter();
        InputSource sheetSource = new InputSource(sheetInputStream);
        try {
            XMLReader sheetParser = SAXHelper.newXMLReader();
            ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, sheetHandler, formatter, false);
            sheetParser.setContentHandler(handler);
            sheetParser.parse(sheetSource);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
        }
    }

/**
     * Initiates the processing of the XLS workbook file to CSV.
     *
     * @throws IOException
     * @throws OpenXML4JException
     * @throws ParserConfigurationException
     * @throws SAXException
     */
    public Map<Integer, List<String[]>> process() throws IOException, OpenXML4JException, ParserConfigurationException, SAXException {
        Map<Integer, List<String[]>> map = new HashMap<>();
        ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage);
        XSSFReader xssfReader = new XSSFReader(this.xlsxPackage);
        StylesTable styles = xssfReader.getStylesTable();
        XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
        int index = 0;
        int length = 0;
        while (iter.hasNext()) {
            InputStream stream = iter.next();
            String sheetName = iter.getSheetName();
            //this.output.println();
            //this.output.println(sheetName + " [index=" + index + "]:");
            if (this.minColumns.length < index + 1) {
                log.info("请求参数不符合sheet页数...直接退出");
                return map;
            }
            processSheet(styles, strings, new SheetToCSV(this.minColumns[index]), stream);
            stream.close();
            //map.put(index, this.rows.subList(length, this.rows.size()));
            length = length + this.rows.size();
            map.put(index, this.rows);
            this.rows = new ArrayList<String[]>();
            ++index;
        }
        return map;
    }

/**
     * 得到excel的记录
     *
     * @param excelPath
     * @param minColumns 输出多少列
     * @return
     * @throws Exception
     */
    public static Map<Integer, List<String[]>> getRecords(String excelPath, int... minColumns) throws Exception {
        File xlsxFile = new File(excelPath);
        if (!xlsxFile.exists()) {
            System.err.println("Not found or not a file: " + xlsxFile.getPath());
            return null;
        }
        // The package open is instantaneous, as it should be.
        OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ);
        XLSX2CSV xlsx2csv = new XLSX2CSV(p, minColumns);
        Map<Integer, List<String[]>> map = xlsx2csv.process();
        p.close();
        return map;
    }

/**
     * 得到excel的记录
     *
     * @param minColumns 输出多少列
     * @return
     * @throws Exception
     */
    public static Map<Integer, List<String[]>> getRecords(File file, int... minColumns) throws Exception {
        OPCPackage p = OPCPackage.open(file);
        XLSX2CSV xlsx2csv = new XLSX2CSV(p, minColumns);
        Map<Integer, List<String[]>> map = xlsx2csv.process();
        p.close();
        return map;
    }

/**
     * Excel列号数字与字母互换
     * Excel column index begin 1
     *
     * @param colStr
     * @param length
     * @return
     */
    public static int excelColStrToNum(String colStr, int length) {
        int num = 0;
        int result = 0;
        for (int i = 0; i < length; i++) {
            char ch = colStr.charAt(length - i - 1);
            num = (int) (ch - 'A' + 1);
            num *= Math.pow(26, i);
            result += num;
        }
        return result;
    }

public static void main(String[] args) throws Exception {

Map<Integer, List<String[]>> map = getRecords("C:\\Users\\lenovo\\Desktop\\333.xlsx", 63, 4, 4);
        int preAscii = excelColStrToNum("AC", 2);
        int curAscii = excelColStrToNum("Z", 1);
        System.out.println(preAscii);
        System.out.println(curAscii);
    }

}

参考文档:https://blog.csdn.net/daiyutage/article/details/53023020

Excel大批量数据导出的更多相关文章

  1. 大批量数据导出到Excel的实现

    在平时的项目中,将数据导出到Excel的需求是很常见的,在此对一些常见的方法做以总结,并提供一种大数据量导出的实现. OLEDB   使用OLEDB可以很方便导出Excel,思路很简单,处理时将Exc ...

  2. 大批量数据导出excel

    有次面试时,老板问我大批量数据一次性导出会有什么问题 感谢度娘提供,感谢原博主提供 https://www.cnblogs.com/zou90512/p/3989450.html

  3. Java:导出Excel大批量数据的优化过程

    背景 团队目前在做一个用户数据看板(下面简称看板),基本覆盖用户的所有行为数据,并生成分析报表,用户行为由多个数据来源组成(餐饮.生活日用.充值消费.交通出行.通讯物流.交通出行.医疗保健.住房物业. ...

  4. jxl写入excel实现数据导出功能

    @RequestMapping(params = "method=export", method = RequestMethod.GET) public void exportCo ...

  5. Java 导出大批量数据excel(百万级)(转载)

    参考资料:http://bbs.51cto.com/thread-1074293-1-1.html                 http://bbs.51cto.com/viewthread.ph ...

  6. Java实现大批量数据导入导出(100W以上) -(三)超过25列Excel导出

    前面一篇文章介绍大数据量导出实现: Java实现大批量数据导入导出(100W以上) -(二)导出 这篇文章在Excel列较少时,按以上实际验证能很快实现生成.但如果列较多时用StringTemplat ...

  7. Java 使用stringTemplate导出大批量数据excel(百万级)

    目前java框架中能够生成excel文件的的确不少,但是,能够生成大数据量的excel框架,我倒是没发现,一般数据量大了都会出现内存溢出,所以,生成大数据量的excel文件要返璞归真,用java的基础 ...

  8. Java实现大批量数据导入导出(100W以上) -(二)导出

    使用POI或JXLS导出大数据量(百万级)Excel报表常常面临两个问题: 1. 服务器内存溢出: 2. 一次从数据库查询出这么大数据,查询缓慢. 当然也可以分页查询出数据,分别生成多个Excel打包 ...

  9. [django]数据导出excel升级强化版(很强大!)

    不多说了,原理采用xlwt导出excel文件,所谓的强化版指的是实现在网页上选择一定条件导出对应的数据 之前我的博文出过这类文章,但只是实现导出数据,这次左思右想,再加上网上的搜索,终于找出方法实现条 ...

随机推荐

  1. pwnable.tw calc

    题目代码量比较大(对于菜鸡我来说orz),找了很久才发现一个能利用的漏洞 运行之发现是一个计算器的程序,简单测试下发现当输入的操作数超过10位时会有一个整型溢出 这里调试了一下发现是printf(&q ...

  2. [JavaScript]ECMA-6 箭头函数

    概述 箭头函数的作用是为Js提供一种函数的简写方法,箭头函数作用域内不包含this, arguments, super, or new.target,并且不能用于对象的构造函数: 基本语法 [(][p ...

  3. Django 之 路由URL,视图,模板,ORM操作

    1.后台管理的左侧菜单,默认只有第一个页签下面的选项是显示的,点了别的页签再显示别的页签下面的选项,问题是:点了任何菜单的选项后,左侧菜单又成了第一个页签的选项显示,别的页签隐藏,也就是左侧的菜单刷新 ...

  4. python socket.error: [Errno 24] Too many open files

    以openwrt AR9331开发板为例,socket连接到1019个就报错 “python socket.error: [Errno 24] Too many open files” 1.查看开发板 ...

  5. James Munkres Topology: Sec 22 Example 1

    Example 1 Let \(X\) be the subspace \([0,1]\cup[2,3]\) of \(\mathbb{R}\), and let \(Y\) be the subsp ...

  6. react native 中实现个别页面禁止截屏

    这里主要用到了原生模块,下面贴出FlagSecureModule.java的代码 package com.studyproj.flagsecure; import android.util.Log; ...

  7. 推荐学习git

    龙恩博客http://www.cnblogs.com/tugenhua0707/p/4050072.html#!comments git命令大全https://www.jqhtml.com/8235. ...

  8. 深入解读Service Mesh背后的技术细节

    在Kubernetes称为容器编排的标准之后,Service Mesh开始火了起来,但是很多文章讲概念的多,讲技术细节的少,所以专门写一篇文章,来解析Service Mesh背后的技术细节. 一.Se ...

  9. hashTabel List 和 dic

    hashTabel  List  和 dic 原:https://www.cnblogs.com/jilodream/p/4219840.html .Net 中HashTable,HashMap 和 ...

  10. BigDecimal.valueOf

    Those are two separate questions: "What should I use for BigDecimal?" and "What do I ...