(タスクスケジューラを使用して)毎日実行し、実行するたびにExcelスプレッドシートに列を追加するJavaプログラムを記述しようとしています。私が抱えている問題は、ファイルに追加するのではなく、単にファイルを再書き込みすることです。私はApache POIを使用しています。関連するコードは次のとおりです。
public static void toExcel(List<String> results, List<Integer> notActive)throws IOException{
try {
FileInputStream fIPS= new FileInputStream("test.xls"); //Read the spreadsheet that needs to be updated
HSSFWorkbook wb;
HSSFSheet worksheet;
if(fIPS.available()>=512) {
wb = new HSSFWorkbook(fIPS); //If there is already data in a workbook
worksheet = wb.getSheetAt(0);
}else{
wb = new HSSFWorkbook(); //if the workbook was just created
worksheet = wb.createSheet("Data");
}
//Access the worksheet, so that we can update / modify it
HSSFRow row1 = worksheet.createRow(0); //0 = row number
int i=0;
Cell c = row1.getCell(i);
while (!(c == null || c.getCellType() == Cell.CELL_TYPE_BLANK)) { //cell is empty
i++;
c=row1.getCell(i);
}
HSSFRow rowx;
int x=0;
for(String s : results) {
rowx = worksheet.createRow(x);
HSSFCell cellx = rowx.createCell(i); //0 = column number
cellx.setCellValue(s);
x++;
}
fIPS.close(); //Close the InputStream
FileOutputStream output_file =new FileOutputStream("test.xls");//Open FileOutputStream to write updates
wb.write(output_file); //write changes
output_file.close(); //close the stream
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
新しい行とセルを何度も作成していて、Excelの書き換えが発生していると思います。
基本的に、プログラムで行とセルを作成する代わりに、それらを取得する必要があります。
HSSFRow row1 = worksheet.createRow(0);
行を作成するのではなく、取得する必要がある場合があります。
HSSFRow row1 = worksheet.getRow(0);
https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Sheet.html#getRow(int)
この小さな例は、2行目の2番目のセルを更新します。
//Read the spreadsheet that needs to be updated
FileInputStream fsIP= new FileInputStream(new File("C:\\Excel.xls"));
//Access the workbook
HSSFWorkbook wb = new HSSFWorkbook(fsIP);
//Access the worksheet, so that we can update / modify it.
HSSFSheet worksheet = wb.getSheetAt(0);
// declare a Cell object
Cell cell = null;
// Access the second cell in second row to update the value
cell = worksheet.getRow(1).getCell(1);
// Get current cell value value and overwrite the value
cell.setCellValue("OverRide existing value");
//Close the InputStream
fsIP.close();
//Open FileOutputStream to write updates
FileOutputStream output_file =new FileOutputStream(new File("C:\\Excel.xls"));
//write changes
wb.write(output_file);
//close the stream
output_file.close();
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加