简体   繁体   中英

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:

    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. 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.

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();
  }
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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