栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java poi将每一个cell设置为文本格式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java poi将每一个cell设置为文本格式

1、在导出excel文件时候,默认导出的数字一般都是数值格式,容易形成科学计数法。   所以我们需要在导出的时候将文件设置为文本格式,比较符合需求。
CellStyle css = wb.createCellStyle();
DataFormat  format = wb.createDataFormat();
css.setDataFormat(format.getFormat("@"));
cell.setCellStyle(css);
需要这四行代码就可以实现设置文本格式,看一下我导出excel文件的模板
  public static void exportExcelNotTitle(HttpServletResponse response, String fileName,
                                 List dataRowList) throws Exception {

    int sheetIndex = 0;
    final int maxRow = 65000;

    final HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet();
    wb.setSheetName(sheetIndex, "Sheet-" + (sheetIndex + 1));

    CellStyle css = wb.createCellStyle();
    DataFormat  format = wb.createDataFormat();
    css.setDataFormat(format.getFormat("@"));
    int rowNum = 0;
    for (final Object dataRow : dataRowList) {

      if (rowNum == maxRow) {
        sheet = wb.createSheet();
        wb.setSheetName(sheetIndex, "Sheet-" + (sheetIndex + 1));
        rowNum = 0;
      }
      HSSFRow row = sheet.createRow(rowNum);
      int cellIndex = 0;
      Class aClass = dataRow.getClass();
      Field[] fields = aClass.getDeclaredFields();
      //反射遍历对象所有属性
      for (final Field field : fields) {
        String name = field.getName();
        Method method = aClass.getMethod("get" + name.substring(0, 1).toUpperCase() + name.substring(1));
        Object data = method.invoke(dataRow);
        HSSFCell cell = row.createCell(cellIndex);
        Object value = data;
        if (value == null) {
          value = "";
        }
        if (value instanceof Date) {
          cell.setCellValue(DateUtils.formatDateTime((Date) value, "yyyy-MM-dd HH:mm:ss"));
        } else {
          cell.setCellValue(value.toString());
        }
//设置文本格式
        cell.setCellStyle(css);
        cellIndex++;
      }
      rowNum++;
    }

    wb.write(getExcelOutputStream(response, fileName));
  }

  public static OutputStream getExcelOutputStream(HttpServletResponse response, String fileName)
      throws Exception {
    return getOutputStream(response, "application/vnd.ms-excel;charset=utf-8", fileName);
  }


 public static OutputStream getOutputStream(HttpServletResponse response, String contentType,
                                             String fileName) throws
      IOException {
    response.setContentType(contentType);
    response.setHeader("Content-Disposition",
        "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

    return response.getOutputStream();
  }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/685209.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号