a problem background
has been following up on the Excel product Bulk publishing function. Last year before the big promotion half month time user frequently uploads the Excel file, causes the on-line machine frequently fullgc. Although not oom, but has been to eat the memory problem. Through heap dump analysis, it is found that the class instance of the POI framework consumes too much memory. The POI framework Developer is aware of this problem by providing a lower-level event pattern to solve the problem of eating memory.
The SS Eventmodel package is a API for reading Excel files without loading to whole into spreadsheet. It does require more knowledge on the "the" of the part of the user, but reduces memory to consumption by more than tenfold. It is based on the AWT event model in combination with SAX. If you are need read-only access, this is the best way to do it.
POI handles Excel to provide a friendly user model and a comparison of the underlying event patterns. User mode provides a good encapsulation, while compatible with 2003 and more than 2007 formats. Provides Hssfworkbook resolution version 03 below Excel, and Xssfworkbook parse 07 version above Excel file, use is quite convenient. The cost, however, is a huge memory cost. Comparing the underlying event pattern requires a combination of SAX technology for reading and less memory consumption. However, the fish and bear cake can not be both, this way the price is to write more of their own code. Two performance test
Do a performance test to compare the memory consumption in both ways.
Performance Test Tool : Jprofiler 9.2,
test data : 45,000 rows of Excel files, 1.8MB
test Machine : MacBook Pro, i7 4 series, Memory 16GB 1. User mode (parsing an Excel object with Xssfworkbook) test Code
/** * @auther * @date 2018/2/5 **/public class Myusermodel {private list<parsedrow> sheetdata = lists.new
ArrayList (); public void Readexcel () {try (Xssfworkbook wb = new Xssfworkbook ("/users/lvsheng/downloads/12/full channel Commodity publishing template-Copy (12)
. xlsx ")) {Xssfsheet sheet = wb.getsheetat (0);
iterator<row> rowiterator = Sheet.rowiterator ();
list<row> list = Lists.newarraylist (Rowiterator);
for (int rowIndex = 0; RowIndex < list.size (); rowindex++) {Parsedrow parsedrow = new Parsedrow ();
Parsedrow.setrowindex (RowIndex);
Row row = List.get (RowIndex);
iterator<cell> celliterator = Row.celliterator ();
list<cell> celllist = lists.newarraylist (celliterator); for (cell cell:celllist) {Parsedrow.getcellmap (). Put (Cell.getcolumnindex (), cell. toString ());
} sheetdata.add (Parsedrow);
} thread.sleep (100000 * 1000);
List.stream (). ForEach (Row-> {short firstcellnum = Row.getfirstcellnum ();
Cell cell = Row.getcell (Firstcellnum);
System.out.println (Cell.tostring ());
});
catch (Exception e) {e.printstacktrace ();
} public static void Main (string[] args) {Myusermodel Myusermodel = new Myusermodel ();
Myusermodel.readexcel (); }
}Jprofiler Monitoring
Memory overview
Object Instances Overview
It's all poi. An instance of an Excel-related memory object generated by the framework
2. Event patterns (combining Sax technology to scan XML documents) test Code
/** * Sax parsing crosses the empty cell because the empty cell does not appear in Sheet.xml at all. When handling cell, the column number should be stored itself * * @auther * @date 2018-02-05 01:07:34 **/public class Myeventusermodel {private static patter
n column_a = Pattern.compile ("A ([\\d]+)");
Private list<parsedrow> Sheetdata = Lists.newarraylist ();
Private Parsedrow RowData = new Parsedrow (); public void Processonesheet (String filename) throws Exception {Opcpackage pkg = opcpackage.open (filename)
;
Xssfreader r = new Xssfreader (pkg);
Sharedstringstable SST = r.getsharedstringstable ();
XMLReader parser = Fetchsheetparser (SST);
To look up the Sheet name/sheet Order/rid,//Your need to process the core workbook stream.
Normally it ' s of the form rid# or rsheet# inputstream Sheet2 = R.getsheet ("RId1");
InputSource Sheetsource = new InputSource (Sheet2);
Parser.parse (Sheetsource);
Sheet2.close (); } public XmlreadeR Fetchsheetparser (sharedstringstable SST) throws Saxexception {XMLReader parser = Xmlreaderfacto
Ry.createxmlreader ("Org.apache.xerces.parsers.SAXParser");
ContentHandler handler = new Sheethandler (SST);
Parser.setcontenthandler (handler);
return parser; }/** * Org.xml.sax.helpers.DefaultHandler Javadocs/Private class Sheethandler extends Defaultha
Ndler {private sharedstringstable SST;
Private String lastcontents;
Private Boolean nextisstring;
private short index;
Private Sheethandler (sharedstringstable sst) {this.sst = SST; @Override public void Startelement (string uri, String localname, string name, Attributes Attributes) th Rows Saxexception {//C => Cell if (name.equals ("C")) {//Print the cell Refe Rence String coordinate = Attributes.getvalue ("R");
Cellreference cellreference = new cellreference (coordinate);
index = Cellreference.getcol ();
Matcher Matcher = column_a.matcher (coordinate); The first line resolves the line number individually if (matcher.matches () && rowdata.getcellmap (). IsEmpty ()) {Rowdat
A.setrowindex (Integer.valueof (Matcher.group (1))-1); } if (Matcher.matches () &&!rowdata.getcellmap (). IsEmpty ()) {Sheetdata.add (R
Owdata);
RowData = new Parsedrow ();
Rowdata.setrowindex (Integer.valueof (Matcher.group (1))-1); }//Figure out if the value is a index in the SST String celltype = Attributes.getvalue
("T");
if (celltype!= null && celltype.equals ("s")) {nextisstring = true; else {nextisstring = false;
}//Clear contents Cache lastcontents = "";
@Override public void EndElement (string uri, String localname, String name) throws Saxexception {
Process the last contents as required. Do now, as characters () May is called more than once if (nextisstring) {int idx = Integer.
parseint (lastcontents);
lastcontents = new Xssfrichtextstring (Sst.getentryat (IDX)). ToString ();
Nextisstring = false; }//V => contents of a cell//Output after we ' ve seen the string contents if (NA
Me.equals ("V")) {Rowdata.getcellmap (). Put (Index.intvalue (), lastcontents); @Override public void Enddocument () throws Saxexception {if (!rowdata.getcellmap
(). IsEmpty ()) { Sheetdata.add (RowData);
} @Override public void characters (char[] ch, int start, int length) throws Saxexception {
Lastcontents + + new String (CH, start, length); } public static void Main (string[] args) throws Exception {String fileName = '/users/lvsheng
/DOWNLOADS/12/Full Channel product release template-Copy (a) xlsx ";
Myeventusermodel example = new Myeventusermodel ();
Example.processonesheet (FileName);
Thread.Sleep (100000 * 1000); }
}Jprofiler Monitoring
Memory overview
Object Instances Overview
three test results Analysis process Memory comparison: User mode 718MB, event mode 191MB, overall memory consumption, both are 3.76:1 user mode will load the entire Excel file information into memory, through the class instance statistics chart can be found, there are a large number of POI framework related to class instances, and a large number of memory consumption. Code comparison: Although the event Mode memory optimization effect is extremely obvious, but this method also has the cost-write more low-level code, the event pattern of code is more than 3 times times the user mode, and in the event pattern requires the Excel file in the structure of XML files know well. four sax Simple introduction
Sax is an alternative to XML parsing, unlike when Dom parses an XML document and loads everything into memory one at a time, scanning the XML document line by row, scanning and parsing. The algorithm is essentially traversing the XML tree first . So those applications that only need to read the content in a single pass can benefit from Sax parsing, which is a huge advantage for parsing large XML documents.