前回質問をさせて頂き、 教えて頂いたプログラムを参考にしましたところうまくいきました。 ところがここでまた1つ問題点が発生してきてしまいました。 業務日報には4つの項目があり、そこを入力すると1行目のDセルまで値が入ります。 次にシステムから上書きをすると正常に2行目に書き込みはされるのですが、1行目のBCDセルの情報が消えてしまい、Aセルのみ残った状態になっています。 これを繰り返すと最新で書き込みした行以外の物はすべてAセルしか情報が残らなくなってしまいます。 この現象を回避するにはどうすればよいのでしょうか? アドバイス宜しくお願いいたします。 public void execute() { FileInputStream in = null; HSSFWorkbook workbook = null; HSSFSheet sheet = null; try { // test.xlsを読み込んでみる // 読み込めた場合は既存のファイルを利用する in = new FileInputStream("test.xls"); workbook = new HSSFWorkbook ( in ); sheet = workbook.getSheetAt ( 0 ); } catch ( IOException e ) { // test.xlsが読み込めない場合はここで新規作成 workbook = new HSSFWorkbook(); sheet = workbook.createSheet("test"); // 見出しを作る Row row = sheet.createRow(0); Cell cell1 = row.createCell(0); Cell cell2 = row.createCell(1); Cell cell3 = row.createCell(2); Cell cell4 = row.createCell(3); cell1.setCellValue("会社"); cell2.setCellValue("報告者"); cell3.setCellValue("場所"); cell4.setCellValue("時間"); } // 行を1行目から走査する // 1行目は見出しのため、チェック対象外 Row row = null; Cell cell1, cell2, cell3, cell4 = null; int i = 1; for ( ; ; i ++ ) { // i番目を取得する row = sheet.getRow(i); if ( row == null ) // i番目が取得できなかったら行を作成 row = sheet.createRow(i); // 0番目のセルを取得する cell1 = row.getCell(0); if ( cell1 == null ) // 0番目のセルが取得できなかったら新規作成 cell1 = row.createCell(0); cell2 = row.createCell(1); cell3 = row.createCell(2); cell4 = row.createCell(3); // そのセルに値が入っていない場合はループを抜ける if ( "".equals(cell1.getStringCellValue()) ) break; } // 値の入っていないセルでループを抜けるため、すなわち最新の行に内容を書き込む cell1.setCellValue(CompanyInput.getText()); cell2.setCellValue(NameInput.getText()); cell3.setCellValue(WhereInput.getText()); contents4.setCellValue(TimeInput.getText()); try { if ( in != null ) in.close(); } catch ( IOException e ) { e.printStackTrace(); } FileOutputStream out = null; try { // ファイルの書き出し out = new FileOutputStream("test.xls"); workbook.write ( out ); } catch ( IOException e ) { e.printStackTrace(); } finally { try { out.close(); } catch ( IOException e ) { e.printStackTrace(); } } } }
↧