为使用ExcelPackage创建的Excel计算单元设置货币格式

时间:2022-07-30 20:24:47

How can I set the currency format for an Excel cell that is created with ExcelPackage?

如何为使用ExcelPackage创建的Excel计算单元设置货币格式?

worksheet.Cell(i, 7).Value = item.Price.ToString();

2 个解决方案

#1


22  

ExcelPackage will read out the NumberFormats on cells. So you can just make a sample in Excel then read out the cells and see what the format is for things you want to do.

ExcelPackage将读出单元格上的数字格式。你可以在Excel中做一个样本然后读出单元格,看看你想要做的事情的格式。

Here is an example of three different ways to format currencies. Note the last one "hardcodes" the $ character, which may not be a best practice.

下面是三种不同的货币格式的示例。注意最后一个“硬编码”$字符,这可能不是最佳实践。

using (ExcelPackage excelPackage = new ExcelPackage(new FileInfo("testReport.xlsx")))
{
  ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add("worksheet");

  ws.Cells[1, 1, 3, 1].Value = 0d;
  ws.Cells[1, 2, 3, 2].Value = -14.957d;
  ws.Cells[1, 3, 3, 3].Value = 5000000.00d;
  ws.Cells[1, 4, 3, 4].Value = -50000000000.00d;
  ws.Cells[1, 1, 1, 4].Style.Numberformat.Format = "#,##0.00;(#,##0.00)";
  ws.Cells[2, 1, 2, 4].Style.Numberformat.Format = "#,##0.00;-#,##0.00";
  ws.Cells[3, 1, 3, 4].Style.Numberformat.Format = "\"$\"#,##0.00;[Red]\"$\"#,##0.00";
  ws.Cells[1, 1, 3, 4].AutoFitColumns();

  excelPackage.Save();
}

#2


9  

ExcelPackage package = new ExcelPackage();
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells[1, 1].Value = 1.50;
worksheet.Cells[1, 1].Style.Numberformat.Format = "$0.00";

This will create $1.50 as a number in your speadsheet

这将在您的speadsheet中创建1.50美元的数字

#1


22  

ExcelPackage will read out the NumberFormats on cells. So you can just make a sample in Excel then read out the cells and see what the format is for things you want to do.

ExcelPackage将读出单元格上的数字格式。你可以在Excel中做一个样本然后读出单元格,看看你想要做的事情的格式。

Here is an example of three different ways to format currencies. Note the last one "hardcodes" the $ character, which may not be a best practice.

下面是三种不同的货币格式的示例。注意最后一个“硬编码”$字符,这可能不是最佳实践。

using (ExcelPackage excelPackage = new ExcelPackage(new FileInfo("testReport.xlsx")))
{
  ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add("worksheet");

  ws.Cells[1, 1, 3, 1].Value = 0d;
  ws.Cells[1, 2, 3, 2].Value = -14.957d;
  ws.Cells[1, 3, 3, 3].Value = 5000000.00d;
  ws.Cells[1, 4, 3, 4].Value = -50000000000.00d;
  ws.Cells[1, 1, 1, 4].Style.Numberformat.Format = "#,##0.00;(#,##0.00)";
  ws.Cells[2, 1, 2, 4].Style.Numberformat.Format = "#,##0.00;-#,##0.00";
  ws.Cells[3, 1, 3, 4].Style.Numberformat.Format = "\"$\"#,##0.00;[Red]\"$\"#,##0.00";
  ws.Cells[1, 1, 3, 4].AutoFitColumns();

  excelPackage.Save();
}

#2


9  

ExcelPackage package = new ExcelPackage();
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells[1, 1].Value = 1.50;
worksheet.Cells[1, 1].Style.Numberformat.Format = "$0.00";

This will create $1.50 as a number in your speadsheet

这将在您的speadsheet中创建1.50美元的数字