如何读写excel文件我想从Java中读取和编写一个包含3列和N行的Excel文件,在每个单元格中打印一个字符串。有人能给我一个简单的代码片段吗?我是否需要使用任何外部库,或者Java是否内置了对它的支持?我想做以下几点: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条经验 获得超3个赞
试试看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
提交
取消
