How to set column names

2019-08-08 17:34发布

问题:

I'm using Apache POI for my app and I want to set columns names instead of "A, B, C..."

I use the following code but it adds just data in first row:

 public void createHeaderRow(HSSFSheet sheet, List<String> headerRowList) {
    HSSFRow headerRow = sheet.createRow(0);
    for(int i=0;i<headerRowList.size();i++){
        HSSFCell cell = headerRow.createCell((short) i);
        cell.setCellValue(headerRowList.get(i).toString());
    }
}

So any ideas?

回答1:

Bad news: AFAIK excel cannot do anything different than A, B, C. The main reason: Column and Row names don't contain information, it's just a numbering. Imagine you want to print a document including these names: Excel won't know about formatting, nor borders, not even cell widths/heights.

You have the following options:

  • Use MS Access which uses database layout (eg Field names as Column names)
  • Fix the first row in the view and format it as table heading. Excel's table autoformat feature does it the same way.


回答2:

For example :

JFileChooser save = new JFileChooser();
        save.setDialogTitle("Save file");
        int chooise = save.showSaveDialog(null);

        File file = null;
        if(chooise == JFileChooser.APPROVE_OPTION){
            file = save.getSelectedFile();
        }

        FileOutputStream fileOut;
        fileOut = new FileOutputStream(file.getAbsolutePath() + ".xls");
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet worksheet = workbook.createSheet("Workbook");
        Row row1 = worksheet.createRow((short)0);
        //Set columt names
        row1.createCell(0).setCellValue("Column Name 0");
        row1.createCell(1).setCellValue("Column Name 1");

etc.