以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<String> rowlist = new ArrayList<String>();
	private int curRow = 0;
	private int curCol = 0;
	private int preCol = 0;
	private int titleRow = 0;
	private int rowsize = 0;
	
	//保存单个sheet数据
	private static List<List<String>> sheetData = new ArrayList<List<String>>();
	
	//保存所有sheet数据
	public static Map sheetMap = new HashMap();

	public void optRows(int sheetIndex, int curRow, List<String> 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<InputStream> 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());
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值