以XML的方式读取Excel文件数据

需要导入POI包
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
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;
import org.xml.sax.helpers.XMLReaderFactory;

@SuppressWarnings({"rawtypes","unchecked"})
public class SheetHandler extends DefaultHandler {

	private SharedStringsTable sst;
	private String lastContents;
	private boolean nextIsString;

	private int sheetIndex = -1;
	private List rowlist = new ArrayList();
	private int curRow = 0;
	private int curCol = 0;
	private int preCol = 0;
	private int titleRow = 0;
	private int rowsize = 0;
	
	//保存单个sheet数据
	private static List> sheetData = new ArrayList>();
	
	//保存所有sheet数据
	public static Map sheetMap = new HashMap();

	public void optRows(int sheetIndex, int curRow, List rowList) {
		List temp = new ArrayList();
		temp.addAll(rowList);
		sheetData.add(temp);
	}

	public void process() throws Exception {
		String filename = "D:/a.xlsx";
		
		OPCPackage pkg = OPCPackage.open(filename);
		XSSFReader r = new XSSFReader(pkg);
		SharedStringsTable sst = r.getSharedStringsTable();
		
		XMLReader parser = fetchSheetParser(sst);

		Iterator sheets = r.getSheetsData();
		// sheets.hasNext()
		while (sheets.hasNext()) {
			curRow = 0;
			sheetIndex++;
			InputStream sheet = sheets.next();
				InputSource sheetSource = new InputSource(sheet);
				parser.parse(sheetSource);
				sheet.close();
				
				//添加到map
				System.out.println("表格"+sheetIndex+"数据长度="+sheetData.size());
				sheetMap.put(sheetIndex, sheetData);
				sheetData = new ArrayList();
			}
	}

	public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
		XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
		this.sst = sst;
		parser.setContentHandler(this);
		return parser;
	}

	public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
		if (name.equals("c")) {
			String cellType = attributes.getValue("t");
			String rowStr = attributes.getValue("r");
			curCol = this.getRowIndex(rowStr);
			if (cellType != null && cellType.equals("s")) {
				nextIsString = true;
			} else {
				nextIsString = false;
			}
		}

		lastContents = "";
	}

	public void endElement(String uri, String localName, String name) throws SAXException {
		if (nextIsString) {
			try {
				int idx = Integer.parseInt(lastContents);
				lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
			} catch (Exception e) {
				//e.printStackTrace();
			}
		}

		if (name.equals("v")) {
			String value = lastContents.trim();
			value = value.equals("") ? " " : value;
			int cols = curCol - preCol;
			if (cols > 1) {
				for (int i = 0; i < cols - 1; i++) {
					rowlist.add(preCol, "");
				}
			}
			preCol = curCol;
			rowlist.add(curCol - 1, value);
		} else {
			if (name.equals("row")) {
				int tmpCols = rowlist.size();
				if (curRow > this.titleRow && tmpCols < this.rowsize) {
					for (int i = 0; i < this.rowsize - tmpCols; i++) {
						rowlist.add(rowlist.size(), "");
					}
				}
				optRows(sheetIndex, curRow, rowlist);
				if (curRow == this.titleRow) {
					this.rowsize = rowlist.size();
				}
				rowlist.clear(); 
				curRow++;
				curCol = 0;
				preCol = 0;
			}
		}
	}

	public void characters(char[] ch, int start, int length) throws SAXException {
		lastContents += new String(ch, start, length);
	}

	public int getRowIndex(String rowStr) {
		rowStr = rowStr.replaceAll("[^A-Z]", "");
		byte[] rowAbc = rowStr.getBytes();
		int len = rowAbc.length;
		float num = 0;
		for (int i = 0; i < len; i++) {
			num += (rowAbc[i] - 'A' + 1) * Math.pow(26, len - i - 1);
		}
		return (int) num;
	}

	public int getTitleRow() {
		return titleRow;
	}

	public void setTitleRow(int titleRow) {
		this.titleRow = titleRow;
	}
	
	public static void main(String[] args) throws Exception{
		SheetHandler p = new SheetHandler();
		p.process();
		System.out.println(p.getRowIndex("1"));
		System.out.println(p.getTitleRow());
	}
}

你可能感兴趣的:(JAVA,数据处理)