How to set column names

£可爱£侵袭症+ 提交于 2019-12-24 13:35:43

问题


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.



来源:https://stackoverflow.com/questions/33080422/how-to-set-column-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!