目前網上能找到的讀取Excel表格中數據的兩種比較好的方案:PageOffice好用開發效率高;POI免費。供你們參考,針對具體狀況選擇具體方案。java
1. PageOffice讀取excel數據庫
import com.zhuozhengsoft.pageoffice.*; import com.zhuozhengsoft.pageoffice.excelreader.*; //讀取Excel單元格數據 Workbook workBook = new Workbook(request, response); Sheet sheet = workBook.openSheet("Sheet1"); Table table = sheet.openTable("A1:F5");while (!table.getEOF()) { //獲取提交的數值 if (!table.getDataFields().getIsEmpty()) { for(int i=0; i<6; i++){ String content = table.getDataFields().get(i).getText(); System.out.println(content);//輸出單元格數據 } } //循環進入下一行 table.nextRow(); } table.close(); workBook.close();
這些代碼只是在服務器端接收客戶端提交的excel單元格數據,PageOffice真正的讀取單元格數據工做是在客戶端執行的,因爲服務器端並無對excel文件作任何讀取操做,只接受一下數據就行,無需耗費大量資源去處理文件,也無需處理多個客戶併發請求的問題,由於每一個客戶端都各自讀取本身的數據,服務器端只接收數據保存到數據庫。apache
2. poi讀取excel服務器
package com.test.poi; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import org.apache.poi.hssf.extractor.ExcelExtractor; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; public class ReadExcel { public static void main(String[] args) throws Exception { HSSFWorkbook wb = null; POIFSFileSystem fs = null; try { fs = new POIFSFileSystem(new FileInputStream("e:\\workbook.xls")); wb = new HSSFWorkbook(fs); } catch (IOException e) { e.printStackTrace(); } HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row = sheet.getRow(0); HSSFCell cell = row.getCell(0); String msg = cell.getStringCellValue(); System.out.println(msg); } public static void method2() throws Exception { InputStream is = new FileInputStream("e:\\workbook.xls"); HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is)); ExcelExtractor extractor = new ExcelExtractor(wb); extractor.setIncludeSheetNames(false); extractor.setFormulasNotResults(false); extractor.setIncludeCellComments(true); String text = extractor.getText(); System.out.println(text); } public static void method3() throws Exception { HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream("e:\\workbook.xls")); HSSFSheet sheet = wb.getSheetAt(0); for (Iterator<Row> iter = (Iterator<Row>) sheet.rowIterator(); iter.hasNext();) { Row row = iter.next(); for (Iterator<Cell> iter2 = (Iterator<Cell>) row.cellIterator(); iter2.hasNext();) { Cell cell = iter2.next(); String content = cell.getStringCellValue();// 除非是sring類型,不然這樣迭代讀取會有錯誤 System.out.println(content); } } } }
注意:HSSFWorkbook,XSSFWorkbook的區別:前者是解析出來excel 2007 之前版本的,後綴名爲xls的,後者是解析excel 2007 版的,後綴名爲xlsx。須要針對不一樣的excel版本編寫不一樣的程序,判斷該用哪一個workbook來對其進行解析處理,並且一般須要開發人員本身把這些方法都作相應封裝,使其更面向對象,工做量有點大,還有就是要求開發高質量代碼,由於是在服務器上執行的,必須解決多個客戶同時請求的併發問題,和萬一程序執行異常的處理問題,上例只是main方法的簡單示例而已,僅供參考!併發