简体   繁体   English

如何将字符串作为货币存储在 java 中的 excel 中?

[英]How to store string as a currency in excel from java?

I want to convert "$122.35"(string) as "$122.35"(currency type) while exporting to excel from java. following is the code snippet:我想在从 java 导出到 excel 时将“$122.35”(字符串)转换为“$122.35”(货币类型)。以下是代码片段:

    HSSFDataFormat df = (HSSFDataFormat) wb.createDataFormat();
                                CellStyle cs = wb.createCellStyle();
                                HSSFCellStyle ct = (HSSFCellStyle) wb.createCellStyle();
                                ct.setDataFormat((short) 7);
                                ct.setAlignment(HorizontalAlignment.RIGHT);
                                cell.setCellStyle(ct);
                                cell.setCellValue(viewCell.getValue());
 // in viewCell.getvalue the currency value is stored 
                                System.out.println("value: ");
                                continue;

If Excel stores text as values for cells then the applied number format does not matter at all.如果 Excel 将文本存储为单元格的值,则应用的数字格式根本无关紧要。 So if number format shall be considered, then the cell value needs to be numeric.因此,如果要考虑数字格式,则单元格值需要是数字。

If you have all values in string format only, then you at least need to know which of them are number types genuinely.如果您只有字符串格式的所有值,那么您至少需要知道其中哪些是真正的数字类型。 In a table, most times all values in one column share the same type.在表中,大多数情况下,一列中的所有值共享相同的类型。 So one could detect the type by column number.因此可以通过列号检测类型。

The task of converting the strings into numbers, could be done using java.time.format.DateTimeFormatter for dates respective java.text.DecimalFormat for numbers.将字符串转换为数字的任务可以使用java.time.format.DateTimeFormatter来完成日期,相应的java.text.DecimalFormat来完成数字。

Complete example to test:要测试的完整示例:

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

public class CreateExcel {
    
 static String[][] sheetData = new String[][] {
  new String[]{"Name", "Date", "Amount"},
  new String[]{"John", "2022-08-17", "$234.56"},
  new String[]{"Jane", "2022-09-15", "$1,234.5"},
  new String[]{"Mary", "2022-07-01", "$1,234,567"},   
  new String[]{"Claire", "2022-06-15", "-$1,234,567.89"},   
  new String[]{"Heidi", "2022-05-01", "-$4,567.8"},   
  new String[]{"Ahmed", "2022-04-15", "-$567"}  
 };
 
 public static void main(String[] args) throws Exception {
     
  DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  //DecimalFormat decimalFormat = (DecimalFormat)NumberFormat.getCurrencyInstance(new Locale("en", "US"));
  DecimalFormat decimalFormat = new DecimalFormat("\u00A4#,##0.00", new DecimalFormatSymbols(new Locale("en", "US")));

  Workbook workbook = new XSSFWorkbook(); String filePath="./ExcelExample.xlsx";
  //Workbook workbook = new HSSFWorkbook(); String filePath="./ExcelExample.xls";
  
  CreationHelper creationHelper = workbook.getCreationHelper();
  CellStyle dateCellStyle = workbook.createCellStyle();
  dateCellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd"));
  CellStyle currencyCellStyle = workbook.createCellStyle();
  currencyCellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("$#,##0.00"));
  
  Sheet sheet = workbook.createSheet();
  for (int r = 0; r < sheetData.length; r++) {
   String[] rowData = sheetData[r];
   Row row = sheet.createRow(r);
   for (int c = 0; c < rowData.length; c++) {
    String cellValue = rowData[c];
    Cell cell = row.createCell(c);
    if (r == 0) {
     cell.setCellValue(cellValue);        
    } else if (c == 0) {
     cell.setCellValue(cellValue);
    } else if (c == 1) {
     LocalDate localDate = LocalDate.parse(cellValue, dateTimeFormatter);   
     cell.setCellValue(localDate);
     cell.setCellStyle(dateCellStyle);   
    } else if (c == 2) {
     Number number = decimalFormat.parse(cellValue);
     cell.setCellValue(number.doubleValue());
     cell.setCellStyle(currencyCellStyle);   
    }    
   }      
  }

  sheet.autoSizeColumn(0);
  sheet.autoSizeColumn(1);
  sheet.autoSizeColumn(2);

  try (FileOutputStream out = new FileOutputStream(filePath)) {
   workbook.write(out);
   workbook.close();
  }
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM