1. 程式人生 > >Excel大檔案解析: Java POI SAX解析Excel 檔案

Excel大檔案解析: Java POI SAX解析Excel 檔案

Java POI SAX Excel xlsx檔案轉CSV

依賴jar 包

gradle:
            compile "org.apache.poi:poi:3.15"
            compile "org.apache.poi:poi-ooxml:3.15"
            compile "org.apache.poi:poi-ooxml-schemas:3.15"
            compile "xerces:xercesImpl:2.11.0"
import lombok.extern.slf4j.Slf4j;
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.ss.util.CellAddress; import org.apache.poi.ss.util.CellReference; 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.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.FileOutputStream; import java.io.IOException; import java.io.InputStream; import static org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler; public class ExcelXlsx2Csv { /** * 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 static class SheetToCSV implements SheetContentsHandler { private boolean firstCellOfRow = false; private int currentRow = -1; private int currentCol = -1; private StringBuffer lineBuffer = new StringBuffer(); /** * Destination for data */ private FileOutputStream outputStream; public SheetToCSV(FileOutputStream outputStream) { this.outputStream = outputStream; } @Override public void startRow(int rowNum) { /** * If there were gaps, output the missing rows: * outputMissingRows(rowNum - currentRow - 1); */ // Prepare for this row firstCellOfRow = true; currentRow = rowNum; currentCol = -1; lineBuffer.delete(0, lineBuffer.length()); //clear lineBuffer } @Override public void endRow(int rowNum) { lineBuffer.append('\n'); try { outputStream.write(lineBuffer.substring(0).getBytes()); } catch (IOException e) { log.error("save date to file error at row number: {}", currentCol); throw new RuntimeException("save date to file error at row number: " + currentCol); } } @Override public void cell(String cellReference, String formattedValue, XSSFComment comment) { if (firstCellOfRow) { firstCellOfRow = false; } else { lineBuffer.append(','); } // gracefully handle missing CellRef here in a similar way as XSSFCell does if (cellReference == null) { cellReference = new CellAddress(currentRow, currentCol).formatAsString(); } int thisCol = (new CellReference(cellReference)).getCol(); //空缺單元格的個數,合併單元格和沒有內容的單元格都算是丟失的col int missedCols = thisCol - currentCol - 1; if (missedCols > 1) { //合併單元格的地方,不列印逗號 lineBuffer.append(','); } currentCol = thisCol; if (formattedValue.contains("\n")) { //去除換行符 formattedValue = formattedValue.replace("\n", ""); } formattedValue = "\"" + formattedValue + "\""; //有些excel文件 2300的數值為2,300 lineBuffer.append(formattedValue); } @Override public void headerFooter(String text, boolean isHeader, String tagName) { // Skip, no headers or footers in CSV } } /** * Parses and shows the content of one sheet * using the specified styles and shared-strings tables. * * @param styles The table of styles that may be referenced by cells in the sheet * @param strings The table of strings that may be referenced by cells in the sheet * @param sheetInputStream The stream to read the sheet-data from. * @throws java.io.IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. * @throws SAXException if parsing the XML data fails. */ private static void processSheet(StylesTable styles, ReadOnlySharedStringsTable strings, SheetContentsHandler sheetHandler, InputStream sheetInputStream) throws Exception { 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 If reading the data from the package fails. * @throws SAXException if parsing the XML data fails. */ public static void process(String srcFile, String destFile) throws Exception { File xlsxFile = new File(srcFile); OPCPackage xlsxPackage = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ); ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(xlsxPackage); XSSFReader xssfReader = new XSSFReader(xlsxPackage); StylesTable styles = xssfReader.getStylesTable(); XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData(); int index = 0; while (iter.hasNext()) { InputStream stream = iter.next(); String sheetName = iter.getSheetName(); log.info(sheetName + " [index=" + index + "]"); FileOutputStream fileOutputStream = new FileOutputStream(destFile); processSheet(styles, strings, new SheetToCSV(fileOutputStream), stream); stream.close(); fileOutputStream.flush(); fileOutputStream.close(); ++index; } xlsxPackage.close(); } public static void main(String[] args) throws Exception { ExcelXlsx2Csv.process("/home/Focuson/桌面/test-1.xlsx", "/home/Focuson/桌面/test-1.csv"); } }

個別細節地方需要自己處理

Java POI SAX Excel xlsx檔案解析

待續

相關推薦

Excel檔案解析 Java POI SAX解析Excel 檔案

Java POI SAX Excel xlsx檔案轉CSV 依賴jar 包 gradle: compile "org.apache.poi:poi:3.15" compile "org.apache.poi

nginx日誌解析java正則解析

背景:     日誌從nginx產生,並實時寫入kafka佇列中,為了便於對海量日誌資料進行離線分析,我們一般將日誌存放到hdfs下,然後通過hive建立外部表使用HQL進行資料統計分析。而要使hive能夠識別日誌資訊,我們必須將日誌內容結構化。將日誌資訊解析成hive能識別的格

Java POI SAX模式 讀取資料Excel

業務描述: 字尾為.xlsx的Excel檔案,只有一個sheet頁,且該sheet頁對應資料庫中的1張表,從A1開始有資料,第1行的資料對應表的各個欄位,從第2行開始是要匯入的資料,將該Excel匯入到資料庫中 解決方案: 因為Excel包含大量資料,如果

Java眼中的XML---檔案讀取(二)SAX解析XML檔案

目錄 (一)SAX解析是什麼? (二)SAX解析和DOM解析的區別? (三)SAX方法解析XML的步驟 (四)SAX解析Java程式碼實現 (一)SAX解析是什麼? SAX(simple API for XML)是一種XML解析的

JAVA POI上傳excel檔案到資料庫並備份(上)

一、電商系統和辦公系統時常會用到Excel的匯入與匯出,在JAVA程式碼實現時,通常使用POI來處理,今天用一個demo為大家介紹POI上傳excel檔案並將資料匯入資料庫的實現過程。demo是一個jsp/servlet+maven的web專案。 二、環境:     資料庫

Java POI 讀寫Excel 檔案簡單實現

整理FileUtils的一些方法,只是一些初步實現,剛寫完就掛上來了… 友情提示:**過於結構化,沒太多潤色....碼的不好還請諸位海涵並多提意見** 關聯的型別 資源 型別 說明 Workbook 介面 Ex

Java使用Sax解析xml檔案

使用java的Sax對xml檔案進行解析,大致可分為以下幾個步驟 1、建立SAXParserFactory例項 2、建立SAXParser例項 3、建立一個繼承自DefaultHandler的handler例項 4、使用handler對xml文件進行解析 一、要解析的b

解決Java POI 導出Excel時文件名中文亂碼,兼容瀏覽器

byte net req response .net str agen odin 中文亂碼 String agent = request.getHeader("USER-AGENT").toLowerCase(); response.setContentTyp

Java編譯(二) Java前端編譯Java原始碼編譯成Class檔案的過程

Java編譯(二)Java前端編譯: Java原始碼編譯成Class檔案的過程               在上篇文章《Java三種編譯方式:前端編

poi匯出Excel Java POI匯入匯出Excel

Java POI匯入匯出Excel   1、異常java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException     解決方法:     

Java POI匯出到Excel

第一次利用POI匯出到Excel,網上看了一些方法,但很多太過於複雜,讓人一下難以看懂,因此在這貼上比較簡單易看懂的方法,方便以後使用。 util類: package com.nian.energy.worksheet.util; import java.io.FileOutputSt

JAVASAX解析XML格式資料--Jdom.jar

package com.yldyyn.test; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.Namespace; import org.

Java POI Mysql與excel間的資料匯入匯出

​ 本文介紹的是利用Apache poi 的api將mysql中的資料匯出到excel表中及將excel表中的資料插入到mysql中。我封裝成了工具類,匯出的時候想匯出哪張表只需要寫sql語句就可以了。匯入到mysql的時候因為我專案中用到了mybatis有與資

Java poi匯出設定 Excel某些單元格不可編輯

 小白的總結,大神勿噴;需要轉載請說明出處,如果有什麼問題,歡迎留言 一、需求: 1、某一列 、某一行或某些單元格不可編輯,其他列可以編輯 二、期間遇到的問題 1、無法設定成不可編輯 2、設定為不可編輯,匯出後發現所有單元格均不可編輯; 原因:createCell();建立單元格後,單元

java poi操作word模版檔案生成表單和修改

使用java poi進行模版檔案的上傳,生成表單,重新生成檔案。同時包括表單中含有下拉框等選項的處理。 XWPFDocument物件POI是apache提供的可以操作word文件的第三方jar。POI能操作word是使用XWPFDocument物件。XWPFDocumen

java poi方式的excel的 匯入匯出demo

由於專案中實際的程式碼比較複雜,這裡就參考下簡單版的匯入匯出函式 匯出excel檔案 其中 response : 響應物件,用於直接返回給瀏覽器。 list: 內容資料,遍歷填充單元格。 filename: 檔名。 title: excel第一行的標題陣列。

JAVA POI批量匯入EXCEL資料到資料庫

首先先記錄下碰到的問題: 原先想直接傳要上傳的檔案路徑到後端,然後後端絕對定位到相應檔案進行資料的解析,後面發現瀏覽器這邊為了安全問題,是不能獲得檔案的真實路徑的,只能獲得一個虛假的路徑,然後這種做法就行不通了,我的解決方法是先把檔案上傳的到後端相關目錄,解析完資料後在將對應

深度解析Java為什麽能夠長盛不衰?

屏蔽 排行 在操作 設計 產品 產品經理 移動 應用開發 深度 Java通常被說成是世界第一的編程語言,是什麽原因讓它這麽受歡迎呢?本文小編就帶你詳細看看Java的相關數據。 TIOBE編程語言排行榜 TIOBE 編程語言社區排行榜是編程語言流行趨勢的一個指標,每月更新,這

[轉] POI SAX 解析 xlsx 包括空單元格處理

1.原文傳送門 2.說明 最近有關於大資料量 Excel07 的解析, 網上搜索了N篇文章, 都不能完美解決空單元格的問題, 直到發現上文, 剛好滿足需要 3.原理 poi先將excel轉為xml,而後是使用SAXParser解析器,解析x

python解析Java環境配置簡化版

1. 下載安裝jdk 怎樣判斷JDK已經安裝成功 windows下:開始->執行->鍵入cmd->在視窗中輸入 javac-> 回車,看看是否出來java相關命令的引數。 ja