创建带有 Java 格式文本的 Excel

当我下载 Excel 时,我得到格式为 Numbers 的单元格,我需要在所有单元格中设置文本格式。


try {

            XSSFSheet sheet = workbook.createSheet(eyelash);


            XSSFFont font = workbook.createFont();

            font.setColor(HSSFColor.WHITE.index);

            XSSFCellStyle style = workbook.createCellStyle();

            style.setFont(font);

            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            style.setFillForegroundColor(HSSFColor.RED.index);



            String[] header = { "name","surname"};

            XSSFRow rowhead = sheet.createRow((short) 0);

            XSSFCell cell;

            int cellnum = 0;


            for (int i = 0; i < header.length; i++) {

                cell = rowhead.createCell(cellnum);

                cell.setCellValue(header[i]);

                cell.setCellStyle(style);

                cell.setCellType(XSSFCell.CELL_TYPE_STRING);

                cellnum++;

            }


            if (data) {

                int myRowData = 1;

                XSSFRow row = sheet.createRow((short) myRowData);

                ArrayList<GasNomination> list = this.select();


                for (int i = 0; i < list.size(); i++) {


                    row.createCell(0).setCellValue(list.get(i).name());

                    row.createCell(1).setCellValue(list.get(i).surname());


                    myRowData++;

                    row = sheet.createRow((short) myRowData);

                }

            }


        } catch (Exception ex) {


        }

我试过 cell.setCellType(XSSFCell.CELL_TYPE_STRING); 但是当我打开 Excel 时,我看到 formatcell 类型为 numeric ...


阿波罗的战车
浏览 149回答 1
1回答

神不在的星期二

您可以使用 DataFormatter,&nbsp; &nbsp; System.out.println("started");&nbsp; &nbsp; XSSFWorkbook workbook = new XSSFWorkbook();&nbsp; &nbsp; XSSFSheet sheet = workbook.createSheet();&nbsp; &nbsp; XSSFRow row = sheet.createRow(0);&nbsp; &nbsp; XSSFCell cell = row.createCell(0);&nbsp; &nbsp; cell.setCellValue(3.14159);&nbsp; &nbsp; cell.setCellType(XSSFCell.CELL_TYPE_STRING);&nbsp; &nbsp; XSSFDataFormat format = workbook.createDataFormat();&nbsp; &nbsp; XSSFCellStyle style = workbook.createCellStyle();&nbsp; &nbsp; style.setDataFormat(format.getFormat("Text"));&nbsp; &nbsp; cell.setCellStyle(style);&nbsp; &nbsp; workbook.write(new FileOutputStream("Test.xlsx"));&nbsp; &nbsp; System.out.println("finished");
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java