[英]How do you read a particular cell's content from multiple sheets in an Excel spreadsheet using Java?
I have a spreadsheet having more than 100 sheets. 我的电子表格有100多张纸。 I have to read a particular cell content eg 7th row 5th column from each sheet and write it in a separate sheet in a single column.
我必须从每个工作表中读取特定的单元格内容,例如第7行第5列,并将其写在单独的工作表中的单列中。
Something like this? 像这样吗
public static List<String> getCellOfAllSheets (File file, int row, int cell) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
List<String> rows = new ArrayList<>(workbook.getNumberOfSheets());
for (int numberOfSheet = 0; numberOfSheet < workbook.getNumberOfSheets(); numberOfSheet++) {
HSSFSheet sheet = workbook.getSheetAt(numberOfSheet);
rows.add(sheet.getRow(row).getCell(cell).getStringCellValue());
}
return rows;
}
I think what you're asking is: For a given row and column location (cell) across many sheets, you want to grab the cell there, then save those values into a new Sheet in a single column. 我想您要问的是:对于许多工作表中给定的行和列位置(单元格),您想要在其中获取该单元格,然后将这些值保存到单列中的新工作表中。 Assuming so
假设是这样
First, open the Workbook, and add in a new sheet: 首先,打开工作簿,并添加一个新表:
Workbook wb = WorkbookFactory.create(new File("input.xlsx"));
Sheet output = wb.createSheet("Found Values");
Next, turn the cell reference (eg D3) into the row and cell indexes, using CellReference : 接下来,使用CellReference将单元格引用(例如D3)转换为行和单元格索引 :
CellReference ref = new CellReference("D3"); // example
int rowWanted = ref.getRow(); // 2
int cellWanted = ref.getCol(); // 3
Now, we iterate over all of other sheets (except our new one!), grabbing the cell of interest, and writing it into the new sheet 现在,我们遍历所有其他工作表(除了新工作表!),获取感兴趣的单元格,然后将其写入新工作表中
for (int sn=0; sn<wb.getNumberOfSheets()-1; sn++) {
Sheet input = wb.getSheetAt(sn);
Row or = output.createRow(sn);
Cell oc = or.createCell(0);
Row ir = input.getRow(rowWanted);
Cell ic = null;
if (ir != null) {
ic = ir.getCell(cellWanted, Row.RETURN_BLANK_AS_NULL);
}
if (ic == null) {
// Empty
oc.setCellValue("No value in " + input.getSheetName());
} else {
// Save the value to the new cell
switch (ic.getCellType()) {
case Cell.CELL_TYPE_STRING:
oc.setCellValue(ic.getRichStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
oc.setCellValue(ic.getNumericCellValue());
oc.setCellStyle(ic.getCellStyle()));
break;
case Cell.CELL_TYPE_BOOLEAN:
oc.setCellValue(ic.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
oc.setCellFormula(ic.getCellFormula());
break;
default:
}
}
}
Finally, we save the updated file out: 最后,我们将更新后的文件保存出来:
FileOutputStream out = new FileOutputStream("output.xlsx");
wb.write(out);
out.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.