Java WebでPOIを使ってExcelをエクスポートする方法の詳細


本論文の実例は、Java WebがPOIを用いてExcelを導出する方法を説明する。皆さんに参考にしてあげます。具体的には以下の通りです。
Spring mvcアーキテクチャを採用する:
Controller層コードは以下の通りです。

@Controller
public class StudentExportController{
  @Autowired
  private StudentExportService studentExportService;
  @RequestMapping(value = "/excel/export")
  public void exportExcel(HttpServletRequest request, HttpServletResponse response)
  throws Exception {
    List<Student> list = new ArrayList<Student>();
    list.add(new Student(1000,"zhangsan","20"));
    list.add(new Student(1001,"lisi","23"));
    list.add(new Student(1002,"wangwu","25"));
    HSSFWorkbook wb = studentExportService.export(list);
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment;filename=student.xls");
    OutputStream ouputStream = response.getOutputStream();
    wb.write(ouputStream);
    ouputStream.flush();
    ouputStream.close();
  }
}

Service層コードは以下の通りです。

@Service
public class StudentExportService {
  String[] excelHeader = { "Sno", "Name", "Age"};
  public HSSFWorkbook export(List<Campaign> list) {
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("Campaign");
    HSSFRow row = sheet.createRow((int) 0);
    HSSFCellStyle style = wb.createCellStyle();
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    for (int i = 0; i < excelHeader.length; i++) {
      HSSFCell cell = row.createCell(i);
      cell.setCellValue(excelHeader[i]);
      cell.setCellStyle(style);
      sheet.autoSizeColumn(i);
    }
    for (int i = 0; i < list.size(); i++) {
      row = sheet.createRow(i + 1);
      Student student = list.get(i);
      row.createCell(0).setCellValue(student.getSno());
      row.createCell(1).setCellValue(student.getName());
      row.createCell(2).setCellValue(student.getAge());
    }
    return wb;
  }
}

フロントのjsコードは以下の通りです。

<script>
function exportExcel(){
   location.href="excel/export" rel="external nofollow" ;
   <!--     ajax  ,ajax             -->
 }
</script>

Excelスタイルと注意点を設定します。

String[] excelHeader = { "    (  )", "  ", "      ", "", "", "", "",
  "", "      ", "", "", "", "", "", "      ", "", "", "      ",
  "", "", "IP    ", "", "", "", "", "     " };
String[] excelHeader1 = { "", "", "  ( )", "  ( )", "  ( )", "  ( )",
  "  ( )", "  ( )", "  ( ) ", "  ( )", "  ( )", "   (M)",
  "    (M)", "    (M)", "  ( )", "  ( )", "  ( )", "    ( )",
  "    ( )", "    ( )", "  ( )", "  ( )", "   ( )", "   ( )",
  "  ( )", "" };
//      
int[] excelHeaderWidth = { 150, 120, 100, 100, 100, 100, 100, 100, 100,
  100, 100, 120, 120, 120, 120, 120, 120, 150, 150, 150, 120,
  120, 150, 150, 120, 150 };
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("      ");
HSSFRow row = sheet.createRow((int) 0);
HSSFCellStyle style = wb.createCellStyle();
//       
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //     
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //     
//       
HSSFCellStyle style1 = wb.createCellStyle();
Font font = wb.createFont();
font.setColor(HSSFColor.RED.index);
font.setBoldweight(Font.BOLDWEIGHT_BOLD); //   
style1.setFont(font);
style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); //     
style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //     
//      
// first row (0-based) last row (0-based) first column (0-based) last
// column (0-based)
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0));
sheet.addMergedRegion(new CellRangeAddress(0, 1, 1, 1));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 2, 7));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 8, 13));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 14, 16));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 17, 19));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 20, 24));
sheet.addMergedRegion(new CellRangeAddress(0, 1, 25, 25));
//      (  )
for (int i = 0; i < excelHeaderWidth.length; i++) {
  sheet.setColumnWidth(i, 32 * excelHeaderWidth[i]);
}
//      
for (int i = 0; i < excelHeader.length; i++) {
  HSSFCell cell = row.createCell(i);
  cell.setCellValue(excelHeader[i]);
  cell.setCellStyle(style);
}
row = sheet.createRow((int) 1);
for (int i = 0; i < excelHeader1.length; i++) {
  HSSFCell cell = row.createCell(i);
  cell.setCellValue(excelHeader1[i]);
  cell.setCellStyle(style);
}

注意点1:セルの結合    new CelRangAddres(int,int,int,int)
first row(0-based)、last row(0-based)、first column(0-based)、last column(0-based)
注意点2:セルの結合
String[]excerHeader="""",""",""","",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",",
結合した後のセルは一つですが、そのセルの内容を保持します。ここでは空の文字列で置換します。そうでないと、後続のヘッダが表示されません。
注意点3:セルを塗りつぶす
正しい書き方:

HSSFCell cell = row.createCell(i);
cell.setCellValue(excelHeader1[i]);
cell.setCellStyle(style);

エラーの書き方:

row.createCell(i).setCellValue(excelHeader1[i]);
row.createCell(i).setCellStyle(style);

本人はHSSFCellオブジェクトを節約するために、誤った書き方をしてHSSFCellオブジェクトを2回作成しました。最後にスタイルだけを残しました。内容は表示できません。
java関連の内容についてもっと興味がある読者は、当駅のテーマを調べてもいいです。「Javaデータ構造とアルゴリズム教程」、「Javaファイルとディレクトリの操作テクニックのまとめ」、「Java操作DOMノード技術のまとめ」、「Javaキャッシュ操作テクニックのまとめ
本論文で述べたように、皆さんのjavaプログラムの設計に役に立ちます。