在實(shí)際應(yīng)用中經(jīng)常需要把Excel表格數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫(kù),為此需求本人寫了一個(gè)讀取Excel數(shù)據(jù)的java類,現(xiàn)將代碼貼出來(lái)與大家一起分享。
該類提供兩個(gè)方法,一個(gè)方法用于讀取Excel表格的表頭,另一個(gè)方法用于讀取Excel表格的內(nèi)容。
(注:本類需要POI組件的支持,POI是apache組織下的一個(gè)開源組件,)
代碼如下:
- package org.hnylj.poi.util;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Map;
- 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;
- /**
- *操作Excel表格的功能類
- *@author:hnylj
- *@version1.0
- */
- public class ExcelReader{
- private POIFSFileSystemfs;
- private HSSFWorkbookwb;
- private HSSFSheetsheet;
- private HSSFRowrow;
- /**
- *讀取Excel表格表頭的內(nèi)容
- *@paramInputStream
- *@returnString表頭內(nèi)容的數(shù)組
- *
- */
- public String[]readExcelTitle(InputStreamis){
- try {
- fs= new POIFSFileSystem(is);
- wb= new HSSFWorkbook(fs);
- } catch (IOExceptione){
- e.printStackTrace();
- }
- sheet=wb.getSheetAt( 0 );
- row=sheet.getRow( 0 );
- //標(biāo)題總列數(shù)
- int colNum=row.getPhysicalNumberOfCells();
- String[]title= new String[colNum];
- for ( int i= 0 ;i<colNum;i++){
- title[i]=getStringCellValue(row.getCell(( short )i));
- }
- return title;
- }
- /**
- *讀取Excel數(shù)據(jù)內(nèi)容
- *@paramInputStream
- *@returnMap包含單元格數(shù)據(jù)內(nèi)容的Map對(duì)象
- */
- public Map<Integer,String>readExcelContent(InputStreamis){
- Map<Integer,String>content= new HashMap<Integer,String>();
- Stringstr= "" ;
- try {
- fs= new POIFSFileSystem(is);
- wb= new HSSFWorkbook(fs);
- } catch (IOExceptione){
- e.printStackTrace();
- }
- sheet=wb.getSheetAt( 0 );
- //得到總行數(shù)
- int rowNum=sheet.getLastRowNum();
- row=sheet.getRow( 0 );
- int colNum=row.getPhysicalNumberOfCells();
- //正文內(nèi)容應(yīng)該從第二行開始,第一行為表頭的標(biāo)題
- for ( int i= 1 ;i<=rowNum;i++){
- row=sheet.getRow(i);
- int j= 0 ;
- while (j<colNum){
- //每個(gè)單元格的數(shù)據(jù)內(nèi)容用"-"分割開,以后需要時(shí)用String類的replace()方法還原數(shù)據(jù)
- //也可以將每個(gè)單元格的數(shù)據(jù)設(shè)置到一個(gè)javabean的屬性中,此時(shí)需要新建一個(gè)javabean
- str+=getStringCellValue(row.getCell(( short )j)).trim()+ "-" ;
- j++;
- }
- content.put(i,str);
- str= "" ;
- }
- return content;
- }
- /**
- *獲取單元格數(shù)據(jù)內(nèi)容為字符串類型的數(shù)據(jù)
- *@paramcellExcel單元格
- *@returnString單元格數(shù)據(jù)內(nèi)容
- */
- private StringgetStringCellValue(HSSFCellcell){
- StringstrCell= "" ;
- switch (cell.getCellType()){
- case HSSFCell.CELL_TYPE_STRING:
- strCell=cell.getStringCellValue();
- break ;
- case HSSFCell.CELL_TYPE_NUMERIC:
- strCell=String.valueOf(cell.getNumericCellValue());
- break ;
- case HSSFCell.CELL_TYPE_BOOLEAN:
- strCell=String.valueOf(cell.getBooleanCellValue());
- break ;
- case HSSFCell.CELL_TYPE_BLANK:
- strCell= "" ;
- break ;
- default :
- strCell= "" ;
- break ;
- }
- if (strCell.equals( "" )||strCell== null ){
- return "" ;
- }
- if (cell== null ){
- return "" ;
- }
- return strCell;
- }
- /**
- *獲取單元格數(shù)據(jù)內(nèi)容為日期類型的數(shù)據(jù)
- *@paramcellExcel單元格
- *@returnString單元格數(shù)據(jù)內(nèi)容
- */
- private StringgetDateCellValue(HSSFCellcell){
- Stringresult= "" ;
- try {
- int cellType=cell.getCellType();
- if (cellType==HSSFCell.CELL_TYPE_NUMERIC){
- Datedate=cell.getDateCellValue();
- result=(date.getYear()+ 1900 )+ "-" +(date.getMonth()+ 1 )
- + "-" +date.getDate();
- } else if (cellType==HSSFCell.CELL_TYPE_STRING){
- Stringdate=getStringCellValue(cell);
- result=date.replaceAll( "[年月]" , "-" ).replace( "日" , "" ).trim();
- } else if (cellType==HSSFCell.CELL_TYPE_BLANK){
- result= "" ;
- }
- } catch (Exceptione){
- System.out.println( "日期格式不正確!" );
- e.printStackTrace();
- }
- return result;
- }
- public static void main(String[]args){
- try {
- //對(duì)讀取Excel表格標(biāo)題測(cè)試
- InputStreamis= new FileInputStream( "C://Excel表格測(cè)試.xls" );
- ExcelReaderexcelReader= new ExcelReader();
- String[]title=excelReader.readExcelTitle(is);
- System.out.println( "獲得Excel表格的標(biāo)題:" );
- for (Strings:title){
- System.out.print(s+ "" );
- }
- //對(duì)讀取Excel表格內(nèi)容測(cè)試
- InputStreamis2= new FileInputStream( "C://Excel表格測(cè)試.xls" );
- Map<Integer,String>map=excelReader.readExcelContent(is2);
- System.out.println( "獲得Excel表格的內(nèi)容:" );
- for ( int i= 1 ;i<=map.size();i++){
- System.out.println(map.get(i));
- }
- } catch (FileNotFoundExceptione){
- System.out.println( "未找到指定路徑的文件!" );
- e.printStackTrace();
- }
- }
- }
通過(guò)該類提供的方法就能讀取出Excel表格中的數(shù)據(jù),數(shù)據(jù)讀取出來(lái)了,其他的,對(duì)這些數(shù)據(jù)進(jìn)行怎樣的操作,要靠你另外寫程序去實(shí)現(xiàn),因?yàn)樵擃愔惶峁┳x取Excel表格數(shù)據(jù)的功能。
說(shuō)明:在該類中有一個(gè)getStringCellValue(HSSFCell cell)方法和一個(gè)getDateCellValue(HSSFCell cell)方法,前一個(gè)方法用于讀取那些為字符串類型的數(shù)據(jù),如果你的Excel表格中填寫的是日期類型的數(shù)據(jù),則你應(yīng)該在readExcelContent(InputStream is)方法里調(diào)用getDateCellValue(HSSFCell cell)方法,因?yàn)槿粽{(diào)用getStringCellValue(HSSFCell cell)方法讀取日期類型的數(shù)據(jù)將得到的是一個(gè)浮點(diǎn)數(shù),這很可能不符合實(shí)際要求。
- 18:39
- 瀏覽 (645)
- 評(píng)論 (1)
- 分類: poi
- 收藏
- 相關(guān)推薦
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

評(píng)論
StringBuffer content = new StringBuffer("");// 文檔內(nèi)容
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(path));
int sheetCount = workbook.getNumberOfSheets();// excel幾張表
for (int i = 0; i < sheetCount; i++) {// 遍歷excel表
HSSFSheet sheet = workbook.getSheetAt(i);// 對(duì)excel的第一個(gè)表引用
int rowCount = sheet.getLastRowNum();// 取得最后一行的下標(biāo)
for (int j = 0; j < rowCount; j++) {// 循環(huán)每一行
HSSFRow row = sheet.getRow(j);// 引用行
if (row == null) {
continue;
} else {
short cellNum = row.getLastCellNum();
for (short m = 0; m < cellNum; m++) {
HSSFCell cell = row.getCell(m);// 引用行中的一個(gè)單元格
if (cell != null) {
int cellType = cell.getCellType();
// CELL_TYPE_NUMERIC 0 數(shù)字
// CELL_TYPE_STRING 1 字符串
// CELL_TYPE_FORMULA 2 公式
// CELL_TYPE_BLANK 3 空格
// CELL_TYPE_BOOLEAN 4 布爾值
// CELL_TYPE_ERROR 5 錯(cuò)誤
switch (cellType) {
// 單元格類型為數(shù)字
case HSSFCell.CELL_TYPE_NUMERIC:
// 取數(shù)字單元格的值
double d = cell.getNumericCellValue();
content.append(String.valueOf(d) + " ");
break;
// 單元格類型為字符串
case HSSFCell.CELL_TYPE_STRING:
String str = cell.getStringCellValue().trim();
if (!str.equals("")) {
content.append(str + " ");
}
break;
// 單元格類型為公式
case HSSFCell.CELL_TYPE_FORMULA:
// 不讀取公式
// String formula = cell.getCellFormula();
// content = content + formula+" ";
break;
// 單元格類型為空白
case HSSFCell.CELL_TYPE_BLANK:
break;
// 單元格類型為布爾值
case HSSFCell.CELL_TYPE_BOOLEAN:
// boolean bool = cell.getBooleanCellValue();
// content = content + bool+" ";
break;
// 單元格類型為錯(cuò)誤
case HSSFCell.CELL_TYPE_ERROR:
// byte errorCode = cell.getErrorCellValue();
// content = content + errorCode+" ";
break;
default:
break;
}
} else {
// content = content + "..." +" ";//沒(méi)有數(shù)據(jù)的單元格使用...填充
}
}
}
content.append("/r");
}
}
return content.toString().trim();
}