在Java中将Excel列格式从数字更改为文本

时间:2019-03-27 11:22:52

标签: java spring-mvc apache-poi

我正在尝试使用所有列/单元格作为文本创建Excel模板。 Excel工作表有5列

这是我的代码:

@RequestMapping(value = "/app/downloadTemplateForAssociateBankingDetails", method = RequestMethod.GET)
public void downloadTemplateForAssociateBankingDetails(HttpServletRequest request,HttpServletResponse response) throws Exception{
  @SuppressWarnings("resource")
  HSSFWorkbook workbook = new HSSFWorkbook();
  HSSFSheet sheet = workbook.createSheet("AssociateBankingTemplate");
  String[] tableColumns = Constants.DATA_MIGRATION_ASSOCIATE_BANKING_EXCEL_HEADERS;
  DataFormat fmt = workbook.createDataFormat();
  CellStyle cellStyle = workbook.createCellStyle();

  Row row = sheet.createRow(0);
  int cellnum = 0;
  for (String key : tableColumns) 
  {
    Cell cell = row.createCell(cellnum++);
    cellStyle.setDataFormat(
        fmt.getFormat("@"));
    cell.setCellStyle(cellStyle);
    cell.setCellValue((String)key);

  }

  try {
    File file = new File("Associate_Banking_Template.xls");
    FileOutputStream out = new FileOutputStream(file);
    workbook.write(out);

    out.close();
    out.flush();

    String mimeType = URLConnection.guessContentTypeFromName(file.getName());
    if (mimeType == null) {
      mimeType = "application/octet-stream";
    }
    response.setContentType(mimeType);
    StringBuilder fileNameSB = new StringBuilder();
    response.setHeader("Content-Disposition", fileNameSB.append("attachment; filename=\"").append(file.getName()).append("\"").toString());
    response.setContentLength((int) file.length());
    InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
    FileCopyUtils.copy(inputStream, response.getOutputStream());
    inputStream.close();
    response.getOutputStream().close();
    response.getOutputStream().flush();
  }
  catch (Exception e) {
    e.printStackTrace();
  }

}

2 个答案:

答案 0 :(得分:1)

谁告诉您该单元格不是文本格式? MS Excel? LibreOffice Calc?

以下代码对我有用,并且应该为您提供文本格式的单元格。

public class TextFormat {

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

    Workbook workbook = new HSSFWorkbook();
    Sheet sheet = workbook.createSheet("sheet");
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(0);
    cell.setCellValue("Text");

    CellStyle cellStyle = workbook.createCellStyle();
    DataFormat fmt = workbook.createDataFormat();
    cellStyle.setDataFormat(fmt.getFormat("@"));
    cell.setCellStyle(cellStyle);

    OutputStream fileOut = new FileOutputStream("workbook.xls");
    workbook.write(fileOut);
    workbook.close();
  }
}

答案 1 :(得分:0)

类似的东西:

Worksheets("Sheet1").Range("A17").NumberFormat = "@"

我不确定,但我认为“ @”表示文本格式。 那仅适用于一个单元格,如果您想要所有单元格,我认为可能是这样的:

Worksheets("Sheet1").Range("B:B").NumberFormat="@"

如果只需要B列

`Worksheets("Sheet1").Range("A:E").NumberFormat="@"` 

如果您希望所有数据都像文本一样被读取。