gpt4 book ai didi

java - 如何在java中的excel文件的同一张表中插入带有值的新行

转载 作者:搜寻专家 更新时间:2023-11-01 02:44:54 24 4
gpt4 key购买 nike

我想在 Excel 工作表中写入时插入新行。

这是我的代码:

public static void addValuesInWorkbook(String pathAndFileName, String sheetName,
int rowNum, String valuesString,String delimeter) {
if(pathAndFileName.length() > 0 && sheetName.length() > 0 && rowNum >= 0 && valuesString.length() > 0 && delimeter.length() > 0)
{
String[] colValues= null;
if("|".equals(delimeter))
colValues = valuesString.split("\\|");
else
colValues = valuesString.split(delimeter);
int cellnum = 0;
FileInputStream fsIP;
try {
fsIP = new FileInputStream(new File(pathAndFileName));
//Read the spreadsheet that needs to be updated
if(rowNum > 0)
{
rowNum--; //As row indexing starts from 0
}
HSSFWorkbook wb = new HSSFWorkbook(fsIP); //Access the workbook
HSSFSheet sheet = wb.getSheet(sheetName);
HSSFRow row = sheet.getRow(((rowNum>0)?rowNum:0));
HSSFCell cell=null;
for(String colValue:colValues)
{ if(row!=null){
cell = row.getCell(cellnum);
if(cell==null)
cell = row.createCell(cellnum);
}
else if (row == null)
{
row =sheet.createRow(rowNum); //Create a row if it does not exist
cell = row.createCell(cellnum);
}

cell.setCellValue(colValue);
cellnum++;
}
fsIP.close(); //Close the InputStream

FileOutputStream output_file =new FileOutputStream(new File(pathAndFileName)); //Open FileOutputStream to write updates

wb.write(output_file); //write changes

output_file.close(); //close the stream
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

值被插入标题(列名) 但无论何时插入新行,它都会替换旧行值。

请帮忙。

最佳答案

这是因为您要在已有值的行索引上创建新行。您需要将现有行向下移动 1 行,因此您要插入行的索引是“空闲的”。

换句话说,“createRow()”总是会创建一个新行和索引 x,无论是否已经存在。

使用 sheet.shiftRows(..)看: https://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFSheet.html#shiftRows(int , 整数, 整数)

第一个参数应该是要插入内容的行的索引,第二个参数是最后一行的编号,第三个参数应该是 1。所以从 x 开始的所有行都将向下移动一行并且你可以在 x 处插入你的行。

示例:每一行都是一行内容。

1 ----------------------
2 ----------------------
3 ---------------------- < you want to insert a new row at index 3
4 ----------------------
5 ----------------------
6 ----------------------
7 ----------------------

shiftRows(3,7,1) 会这样做:

1 ----------------------
2 ----------------------
3 empty row
4 ---------------------- < your "old" row #3
5 ----------------------
6 ----------------------
7 ----------------------
8 ----------------------

createRow(3),设置单元格值:

1 ----------------------
2 ----------------------
3 ////////////////////// < your new row #3 witht he new content
4 ---------------------- < your "old" row #3
5 ----------------------
6 ----------------------
7 ----------------------
8 ----------------------

关于java - 如何在java中的excel文件的同一张表中插入带有值的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24927438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com