現在、poiで日報システムを作成しております。 入力されたデータはexcelに出力されるような処理をしました。 日報を入力し、ボタンを押されるたびに既存のexcelファイルに上書きされるようにしたいです。 もしエクセルが新規で出力される場合には1行目には見出しを、2行目には入力された内容が出力されます。 次にこのシステムを使った人が書き込みをした場合には3行目に内容が出力されるようにしていきたいです。 このためにexcelを読み込んで、空白セルを確認する処理をすればいいのでしょうが、試行錯誤しました、まず自分で保存先に空のExcelを作らないといけないということと、1回目の入力では正常に2行目まで出力されていますが、もう1度入力をし、出力をすると1,2行目が消えて3行目に書き込みがされるだけになってしまいます。 そこで2点ございます。 (1)2回目の出力で1,2行目が消えてしまうのはプログラムの組み方に誤りがあるのでしょうが、お手上げ状態です。 (2)excelが存在しない場合はこのシステム上で新たに作成をしてくれるようにもできるのでしょうか? ご教授いただければと思います。 public void ExcelOutput() { Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet(); /* * ファイルを読み込みし行数が「0」 * 何も書き込みがされていない場合にはヘッダと1つめの行(2行目)を書き込み */ if(ExcelInput() == 0){ Row head = sheet.createRow(0); Cell head1 = head.createCell(0); Cell head2 = head.createCell(1); head1.setCellValue("会社"); head2.setCellValue("報告者"); CellStyle styleHead = wb.createCellStyle(); styleHead.setFillPattern(CellStyle.SOLID_FOREGROUND); styleHead.setFillForegroundColor(IndexedColors.RED.getIndex()); head1.setCellStyle(styleHead); head2.setCellStyle(styleHead); Row contents = sheet.createRow(1); Cell contents1 = contents.createCell(0); Cell contents2 = contents.createCell(1); contents1.setCellValue(CompanyInput.getText()); contents2.setCellValue(NameInput.getText()); FileOutputStream out = null; try{ out = new FileOutputStream("ccc.xls"); wb.write(out); }catch(IOException e){ //System.out.println(e.toString()); }finally{ try { out.close(); }catch(IOException e){ //System.out.println(e.toString()); } } } /* * すでにエクセル作成済み(1,2行目に入力がされている)場合 * 途中から書き込み */ else{ Row contents = sheet.createRow(CompanyExcelInput()); Cell contents1 = contents.createCell(0); Cell contents2 = contents.createCell(1); contents1.setCellValue(InterviewPersonInput.getText()); contents2.setCellValue(NameInput.getText()); FileOutputStream out = null; try{ out = new FileOutputStream("ccc.xls"); wb.write(out); }catch(IOException e){ //System.out.println(e.toString()); }finally{ try { out.close(); }catch(IOException e){ //System.out.println(e.toString()); } } } } public int ExcelInput(){ int rowNullCount = 0; try{ //Excelのワークブックを読み込む POIFSFileSystem filein = new POIFSFileSystem (new FileInputStream("ccc.xls")); HSSFWorkbook wb = new HSSFWorkbook(filein); //シートを読み込む HSSFSheet sheet = wb.getSheetAt(0); //空行を検索し、空行を保持する for(rowNullCount = 0; rowNullCount <= sheet.getLastRowNum(); rowNullCount++) { HSSFRow row = sheet.getRow(rowNullCount); if(row == null){ break; } } } catch(IOException ioe) { // TODO } return rowNullCount; } ExcelInputとExcelOutputはボタンのactionPerformedで読み込んでいます。 宜しくお願い致します。
↧