자바 는 poi 를 사용 하여 엑셀 데 이 터 를 읽 습 니 다 (엑셀 이 클 수 있 습 니 다. csv 로 변환 한 다음 읽 습 니 다)
-- -- -- -- -- 설정 -- -- -- -- --
jdbc. properties 에 추가: excelUrl =/... xlsx 파일 디 렉 터 리 경로/(excelUrl + "xxxx. xlsx"는 전체 경로)
poi - 3.16 의 jar 가방 6 개, poi - 3.16/lib 의 jar 가방 5 개, poi - 3.16/ooxml - lib 의 jar 가방 2 개 가 져 오기
Excelreader. java 와 XLsXCSV. java 가 져 오기 항목
-- -- -- 방법 -- -- -- -- --
Excel_reader 클래스 의:
xlsx_reader(String excel_name , ArrayList args)
//excel_name 은 읽 을 xlsx 파일 이름 (접미사 포함), args 는 가 져 올 열 번호 의 목록 입 니 다.
//2 차원 배열 Array List > 1 차원 은 xlsx 의 줄 을 표시 하고 2 차원 은 xlsx 의 셀 을 표시 합 니 다.
//빈 칸 을 null 로 되 돌려 주 려 면 - 또는 0 으로 처리 해 야 합 니 다.
//args 는 int 나 String 을 쓸 수 있 습 니 다. args [i] 가 int 라면 되 돌아 오 는 2 차원 배열 의 I 열 은 xlsx 의 제 args [i] 열 입 니 다.
//args [i] 가 String 이면 돌아 오 는 2 차원 배열 의 i 열 은 문자 상수 입 니 다.
//예 를 들 어 xlsxreader ("숭 명 현 - 표 15:"하 담 "녹색 잎 채소 재배 보조금 - 2014. xlsx", args)
//그 중 args = [7, 8, 9, "녹비"]
//그러면 돌아 오 는 2 차원 배열 의 내용 은 다음 과 같다.
[소명, 350401219948383 * * *, null, 녹비]
[소 홍, 6453543543323 * * *, null, 녹비]
[소란 아, 445353453425643 * * *, null, 녹비]
......
XLSX2CSV.java
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
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.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler;
import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor;
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;
/**
* A rudimentary XLSX -> CSV processor modeled on the
* POI sample program XLS2CSVmra from the package
* org.apache.poi.hssf.eventusermodel.examples.
* As with the HSSF version, this tries to spot missing
* rows and cells, and output empty entries for them.
*
* Data sheets are read using a SAX parser to keep the
* memory footprint relatively small, so this should be
* able to read enormous workbooks. The styles table and
* the shared-string table must be kept in memory. The
* standard POI styles table class is used, but a custom
* (read-only) class is used for the shared string table
* because the standard POI SharedStringsTable grows very
* quickly with the number of unique strings.
*
* For a more advanced implementation of SAX event parsing
* of XLSX files, see {@link XSSFEventBasedExcelExtractor}
* and {@link XSSFSheetXMLHandler}. Note that for many cases,
* it may be possible to simply use those with a custom
* {@link SheetContentsHandler} and no SAX code needed of
* your own!
*/
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 class SheetToCSV implements SheetContentsHandler {
private boolean firstCellOfRow = false;
private int currentRow = -1;
private int currentCol = -1;
private void outputMissingRows(int number) {
for (int i = 0; i < number; i++) {
curstr = new ArrayList();
for (int j = 0; j < minColumns; j++) {
curstr.add(null);
}
output.add(curstr);
}
}
@Override
public void startRow(int rowNum) {
curstr = new ArrayList();
// If there were gaps, output the missing rows
outputMissingRows(rowNum - currentRow - 1);
// Prepare for this row
firstCellOfRow = true;
currentRow = rowNum;
currentCol = -1;
}
@Override
public void endRow(int rowNum) {
// Ensure the minimum number of columns
for (int i = currentCol; i < minColumns ; i++) {
curstr.add(null);
}
output.add(curstr);
}
@Override
public void cell(String cellReference, String formattedValue,
XSSFComment comment) {
// if (firstCellOfRow) {
// firstCellOfRow = false;
// } else {
// curstr.append(',');
// }
// gracefully handle missing CellRef here in a similar way as XSSFCell does
if (cellReference == null) {
cellReference = new CellAddress(currentRow, currentCol).formatAsString();
}
// Did we miss any cells?
int thisCol = (new CellReference(cellReference)).getCol();
int missedCols = thisCol - currentCol - 1;
for (int i = 0; i < missedCols; i++) {
curstr.add(null);
}
currentCol = thisCol;
// Number or string?
try {
Double.parseDouble(formattedValue);
curstr.add(formattedValue);
} catch (NumberFormatException e) {
// output.append('"');
curstr.add(formattedValue);
// output.append('"');
}
}
@Override
public void headerFooter(String text, boolean isHeader, String tagName) {
// Skip, no headers or footers in CSV
}
}
///////////////////////////////////////
private final OPCPackage xlsxPackage;
/**
* Number of columns to read starting with leftmost
*/
private final int minColumns;
/**
* Destination for data
*/
private ArrayList> output;
private ArrayList curstr;
public ArrayList> get_output(){
return output;
}
/**
* Creates a new XLSX -> CSV converter
*
* @param pkg The XLSX package to process
* @param output The PrintStream to output the CSV to
* @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 void process()
throws IOException, OpenXML4JException, ParserConfigurationException, SAXException {
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;
while (iter.hasNext()) {
output = new ArrayList> ();
InputStream stream = iter.next();
String sheetName = iter.getSheetName();
System.out.println(" sheet: "+sheetName + " [index=" + index + "]:");
processSheet(styles, strings, new SheetToCSV(), stream);
System.out.println("sheet !");
stream.close();
++index;
}
}
// public static void main(String[] args) throws Exception {
// /* if (args.length < 1) {
// System.err.println("Use:");
// System.err.println(" XLSX2CSV [min columns]");
// return;
// }*/
//
// File xlsxFile = new File("F:\\8 .xlsx");
// if (!xlsxFile.exists()) {
// System.err.println("Not found or not a file: " + xlsxFile.getPath());
// return;
// }
//
// int minColumns = -1;
// if (args.length >= 2)
// minColumns = Integer.parseInt(args[1]);
//
// // The package open is instantaneous, as it should be.
// OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ);
// XLSX2CSV xlsx2csv = new XLSX2CSV(p, System.out, minColumns);
// xlsx2csv.process();
// p.close();
// }
}
Excel_reader.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Excel_reader {
// *************xlsx ************************
// jdbc.properties excelUrl:xlsx
// excel_name ,arg ( , )
//
@SuppressWarnings({ "resource", "unused" })
public static ArrayList> xlsx_reader(String excel_name, ArrayList
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.