poi操作excel之: 将NUMERIC转换成TEXT

没办法,企业业务系统总是避免不了要使用excel进行导入和导出,本代码使用的poi版本是3.16:

一、NUMERIC TO TEXT(生成excel)

代码生成一个excel文件:

public static void generateExcel() throws Exception {
        XSSFWorkbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("天下霸唱");
        sheet.setColumnWidth(0, 10000);  // 设置excel一列的宽度

        // one style
        Font font = workbook.createFont();
        font.setFontName("微软雅黑");
        font.setBold(true);
        font.setFontHeightInPoints((short) 14);

        Font font1 = workbook.createFont();
        font1.setFontName("微软雅黑");
        font1.setFontHeightInPoints((short) 14);

        XSSFCellStyle centerAlignStyle = workbook.createCellStyle();
        centerAlignStyle.setAlignment(HorizontalAlignment.CENTER);
        centerAlignStyle.setVerticalAlignment(VerticalAlignment.CENTER);      // 上下垂直居中
        centerAlignStyle.setFont(font);      //设置字体
        centerAlignStyle.setWrapText(true);   // 换行

        XSSFCellStyle centerAlignStyle1 = workbook.createCellStyle();
        centerAlignStyle1.setAlignment(HorizontalAlignment.CENTER);
        centerAlignStyle1.setVerticalAlignment(VerticalAlignment.CENTER);
        centerAlignStyle1.setFont(font1);

        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("一个值");
        cell.setCellStyle(centerAlignStyle);

        Row row1 = sheet.createRow(1);
        Cell cell1 = row1.createCell(0);
        cell1.setCellValue(String.valueOf(1242532523632L));
        cell1.setCellStyle(centerAlignStyle1);

        Row row2 = sheet.createRow(2);
        Cell cell2 = row2.createCell(0);
        cell2.setCellValue("00000000000009");
        cell2.setCellStyle(centerAlignStyle1);

        FileOutputStream outputStream = new FileOutputStream("test.xlsx");
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
    }

    public static void main(String[] args) throws Exception {
        generateExcel();
    }

生成的excel如下:
这里写图片描述

但你用鼠标点进A2和A3,然后移出鼠标,变成了:
这里写图片描述

在常规模式下,excel就将数值格式化成那样了,如果你将常规设置成文本那就是正常的字符串了。

要让数值不被excel格式化,只需加入下面这行代码:

centerAlignStyle1.setDataFormat(BuiltinFormats.getBuiltinFormat("text"));     // 设置为文本

再次运行你的代码,你应该发现这个神奇的效果了。

二、NUMERIC TO TEXT(读取excel)

要是excel已经是下面这样了:
这里写图片描述

Java代码在读取的时候想要的是字符串:1242532523632,那怎么办?

public static String getCellStringValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        CellType type = cell.getCellTypeEnum();
        String cellValue;
        switch (type) {
            case BLANK:
                cellValue = "";
                break;
            case _NONE:
                cellValue = "";
                break;
            case ERROR:
                cellValue = "";
                break;
            case BOOLEAN:
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case NUMERIC:
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            case STRING:
                cellValue = cell.getStringCellValue();
                break;
            case FORMULA:
                cellValue = cell.getCellFormula();
                break;
            default:
                cellValue = "";
                break;
        }
        return cellValue;
    }

    public static void readExcel() throws Exception {
        FileInputStream inputStream = new FileInputStream(new File("test.xlsx"));
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheetAt(0);
        Cell cell = sheet.getRow(1).getCell(0);
        String cellValue = getCellStringValue(cell);
        System.out.println(cellValue);

        workbook.close();
        inputStream.close();
    }

    public static void main(String[] args) throws Exception {
        readExcel();
    }

上面的执行的结果是:

1.242532523632E12    //不是我们想要的字符串呢

那就使用poi的另一个神器NumberToTextConverter,改写switch的代码:

 case NUMERIC:
 // 改成这样
                cellValue = NumberToTextConverter.toText(cell.getNumericCellValue());
                break;

执行后返回:

1242532523632      //我们想要的结果

That’s all, 哈哈!
Google英文搜索关键字:

excel poi get text value from a numeric cell
excel poi format a cell to text type

参考链接:
https://stackoverflow.com/questions/36018660/how-to-set-a-cell-format-to-text
https://www.programcreek.com/java-api-examples/index.php?api=org.apache.poi.ss.util.NumberToTextConverter

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在使用POIExcel转换为HTML时,日期格式的转换需要注意一些问题。下面是一个示例代码,演示如何使用POIExcel中的日期格式转换为HTML中的日期格式: ```java import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.util.CellAddress; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelToHtmlConverter { public static void main(String[] args) throws IOException { // 读取Excel文件 Workbook workbook = WorkbookFactory.create(ExcelToHtmlConverter.class.getResourceAsStream("test.xlsx")); // 创建HTML文件 FileOutputStream fos = new FileOutputStream("test.html"); // 输出HTML头部 StringBuilder sb = new StringBuilder(); sb.append("<html>"); sb.append("<head>"); sb.append("<meta charset=\"UTF-8\">"); sb.append("</head>"); sb.append("<body>"); sb.append("<table>"); // 遍历每个Sheet for (int i = 0; i < workbook.getNumberOfSheets(); i++) { // 获取当前Sheet String sheetName = workbook.getSheetName(i); sb.append("<tr>"); sb.append("<td colspan=\"100%\" style=\"font-size: 20px; font-weight: bold; text-align: center;\">"); sb.append(sheetName); sb.append("</td>"); sb.append("</tr>"); // 遍历每行数据 for (int j = 0; j < workbook.getSheetAt(i).getPhysicalNumberOfRows(); j++) { sb.append("<tr>"); // 遍历每列数据 for (int k = 0; k < workbook.getSheetAt(i).getRow(j).getLastCellNum(); k++) { Cell cell = workbook.getSheetAt(i).getRow(j).getCell(k); if (cell != null) { CellAddress cellAddress = cell.getAddress(); DataFormatter dataFormatter = new DataFormatter(); String cellValue = dataFormatter.formatCellValue(cell); switch (cell.getCellType()) { case STRING: sb.append("<td>"); sb.append(cellValue); sb.append("</td>"); break; case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String dateString = sdf.format(date); sb.append("<td>"); sb.append(dateString); sb.append("</td>"); } else { sb.append("<td>"); sb.append(cell.getNumericCellValue()); sb.append("</td>"); } break; case BOOLEAN: sb.append("<td>"); sb.append(cell.getBooleanCellValue()); sb.append("</td>"); break; case FORMULA: sb.append("<td>"); sb.append(cell.getCellFormula()); sb.append("</td>"); break; default: sb.append("<td>"); sb.append(""); sb.append("</td>"); break; } } else { sb.append("<td>"); sb.append(""); sb.append("</td>"); } } sb.append("</tr>"); } } // 输出HTML尾部 sb.append("</table>"); sb.append("</body>"); sb.append("</html>"); // 写入HTML文件 fos.write(sb.toString().getBytes()); fos.close(); // 关闭workbook workbook.close(); } } ``` 在上面的代码中,我们使用了POI库的DataFormatter类来获取单元格中的值,并判断单元格是否为日期格式。如果单元格为日期格式,则使用SimpleDateFormat类将日期格式转换为字符串格式。最后,我们将Excel中的数据输出为HTML文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值