在上传excel功能中,对于很大的excel文件直接上传往往会因为文件太大导致内存溢出上传失败,poi提供了首先把excel转为csv再读取上传的方法,在此记录一下。
所需jar包 maven pom.xml配置:
org.apache.poi
poi
4.1.0
org.apache.poi
poi-ooxml
4.1.0
新建XLSXCovertCSVReader工具类
package com.ways.app.framework.base;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.BuiltinFormats;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
/**
* 使用CVS模式解决XLSX文件,可以有效解决用户模式内存溢出的问题
*/
public class XLSXCovertCSVReader {
enum xssfDataType {
BOOL, ERROR, FORMULA, INLINESTR, SSTINDEX, NUMBER,
}
class MyXSSFSheetHandler extends DefaultHandler {
private int isNotNullIndex;
private StylesTable stylesTable;
private ReadOnlySharedStringsTable sharedStringsTable;
private final PrintStream output;
private final int minColumnCount;
private boolean vIsOpen;
private xssfDataType nextDataType;
private short formatIndex;
private String formatString;
private final DataFormatter formatter;
private int thisColumn = -1;
private int lastColumnNumber = -1;
private StringBuffer value;
private String[] record;
private List rows = new ArrayList();
private boolean isCellNull = false;
public MyXSSFSheetHandler(StylesTable styles,ReadOnlySharedStringsTable strings, int cols, PrintStream target</