如何讀寫excel文件我想從Java中讀取和編寫一個包含3列和N行的Excel文件,在每個單元格中打印一個字符串。有人能給我一個簡單的代碼片段嗎?我是否需要使用任何外部庫,或者Java是否內(nèi)置了對它的支持?我想做以下幾點:for(i=0; i <rows; i++)
//read [i,col1] ,[i,col2], [i,col3]for(i=0; i<rows; i++)
//write [i,col1], [i,col2], [i,col3]
3 回答

DIEA
TA貢獻1820條經(jīng)驗 獲得超2個贊
試試看Apache POI HSSF..下面是如何讀取Excel文件的示例:
try?{ ????POIFSFileSystem?fs?=?new?POIFSFileSystem(new?FileInputStream(file)); ????HSSFWorkbook?wb?=?new?HSSFWorkbook(fs); ????HSSFSheet?sheet?=?wb.getSheetAt(0); ????HSSFRow?row; ????HSSFCell?cell; ????int?rows;?//?No?of?rows ????rows?=?sheet.getPhysicalNumberOfRows(); ????int?cols?=?0;?//?No?of?columns ????int?tmp?=?0; ????//?This?trick?ensures?that?we?get?the?data?properly?even?if?it?doesn't?start?from?first?few?rows ????for(int?i?=?0;?i?<?10?||?i?<?rows;?i++)?{ ????????row?=?sheet.getRow(i); ????????if(row?!=?null)?{ ????????????tmp?=?sheet.getRow(i).getPhysicalNumberOfCells(); ????????????if(tmp?>?cols)?cols?=?tmp; ????????} ????} ????for(int?r?=?0;?r?<?rows;?r++)?{ ????????row?=?sheet.getRow(r); ????????if(row?!=?null)?{ ????????????for(int?c?=?0;?c?<?cols;?c++)?{ ????????????????cell?=?row.getCell((short)c); ????????????????if(cell?!=?null)?{ ????????????????????//?Your?code?here ????????????????} ????????????} ????????} ????}}?catch(Exception?ioe)?{ ????ioe.printStackTrace();}
在文檔頁上,您也有如何寫入Excel文件的示例。
添加回答
舉報
0/150
提交
取消