java 使用 Apache POI 向 Excel 添加列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28394100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding column to Excel using Apache POI
提问by Biswadip Dey
I was wondering about adding new column in a .xlsx file using apache poi. But I could not found anything. Is there any way to do this? Or is there exists any other library to solve this? Thanks in advance.
我想知道如何使用 apache poi 在 .xlsx 文件中添加新列。但我什么也找不到。有没有办法做到这一点?或者是否存在任何其他库来解决这个问题?提前致谢。
回答by Tejus Prasad
There is no explicit way of doing this using apache POI. If you know the number of rows and the number of columns that you need, you can first create the required number of rows and then create the corresponding cells in the rows. You can refer to the code below if needed.
使用 apache POI 没有明确的方法来做到这一点。如果您知道所需的行数和列数,则可以先创建所需的行数,然后在行中创建相应的单元格。如果需要,您可以参考下面的代码。
for(row=0;row<maxRowLimit;row++){
myRow = sheet.getRow(row);
if (myRow == null) {
myRow = sheet.createRow(row);
myCell=myRow.getCell(columnNumber);
if (myCell == null)
myRow.createCell(columnNumber);
}
}
回答by harsha
If you have excel file with existing rows, well defined, the fastest way to add column is to iterate once over the rows and in each iterations add a column at end as beflow code
如果您有包含现有行的 excel 文件,定义明确,添加列的最快方法是在行上迭代一次,并在每次迭代中在末尾添加一列作为 beflow 代码
FileInputStream excelFile = new FileInputStream(new File(fileDirectory+file));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
// Add additional column for results
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Cell cell = currentRow.createCell(currentRow.getLastCellNum(), CellType.STRING);
if(currentRow.getRowNum() == 0)
cell.setCellValue("NEW-COLUMN");
}
Hope it helps, I assume your first row is header, the rest will be empty for future modifications
希望它有所帮助,我假设您的第一行是标题,其余的将为将来修改为空