[英]How to read Excel (.xlsx) file in java?
從給定的.xlsx
文件,我試圖使用Java讀取數據。
我的閱讀文件代碼如下:
public static void main(String[] args) throws Exception {
FileInputStream file = new FileInputStream(new File("E:\\test1.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet test = workbook.getSheetAt(0);
student emp = new student();
Iterator<Row> itr = test.iterator();
itr.next();
while(itr.hasNext()){
Row row = itr.next();
emp.reedData(row);
System.out.println(id+","+name+","+options);
}
方法如下:
void reedData(Row row){
id= row.getCell(0).toString();
name= row.getCell(1).toString();
options= row.getCell(2).toString();
}
但是,我得到這樣的輸出:
1.0,X,play game
,,sing song
2.0,Y,play game
,,sing song
而不是上面,我希望輸出看起來像這樣:
1.0,X,{play game,sing song}
2.0,Y,{play game,sing song}
這個問題是因為我在.xlsx
文件中合並兩個單元格。
有什么建議嗎? 先感謝您..
這就是我做到的。
import static java.lang.System.out;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class read {
public static void main(String [] args){
FileInputStream excelFile = new FileInputStream(new File(keep));
XSSFWorkbook wb = new XSSFWorkbook(excelFile);
XSSFSheet sheet = wb.getSheetAt(0);
int rowCount; // number of rows of newly form excel files
rowCount= sheet.getPhysicalNumberOfRows();
out.println(rowCount);
//trying to iterate the excel file
int i =0;
Iterator<Row> rowIterator = sheet.iterator();
do{
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(cell.getColumnIndex()==0) { // to read the first column
DataFormatter df = new DataFormatter();
String str2 = df.formatCellValue(cell);
customerNo.add(str2);
}
}
++i;
if(i>rowCount)break;
//break;
}while(rowIterator.hasNext());
wb.close();
}
}
希望這可以幫助。
看起來您正在使用Apache POI。 嘗試將代碼中的這兩個單元格合並為:
test.addMergedRegion(1,2,0,0);
要么:
sheet.addMergedRegion(new CellRangeAddress(1,2,0,0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.