C# 格式化 Excel 单元格(货币)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14338156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Formatting Excel cells (currency)
提问by soundslogic
I developed an Add-In for Excel so you can insert some numbers from a MySQL database into specific cells. Now I tried to format these cells to currency and I have two problems with that. 1. When using a formula on formatted cells, the sum for example is displayed like that: "353,2574". What do I have to do to display it in an appropriate way? 2. Some cells are empty but have to be formatted in currency as well. When using the same format I used for the sum formula and type something in, there's only the number displayed. No "", nothing. What is that? I specified a Excel.Range and used this to format the range
我开发了一个 Excel 插件,这样你就可以将 MySQL 数据库中的一些数字插入到特定的单元格中。现在我尝试将这些单元格格式化为货币,但我有两个问题。1. 在格式化单元格上使用公式时,例如总和显示为:“353,2574”。我该怎么做才能以适当的方式显示它?2. 一些单元格是空的,但也必须以货币格式进行格式化。当使用我用于求和公式的相同格式并输入内容时,只显示数字。没什么。那是什么?我指定了一个 Excel.Range 并用它来格式化范围
sum.NumberFormat = "#.## ";
But I also tried
但我也试过
sum.NumberFormat = "0,00 ";
sum.NumberFormat = "#.##0,00 ";
Any idea someone?
有人知道吗?
采纳答案by Jobert Enamno
This one works for me. I have excel test app that formats the currency into 2 decimal places with comma as thousand separator. Below is the Console Application that writes data on Excel File.
这个对我有用。我有 excel 测试应用程序,它将货币格式化为 2 个小数位,以逗号作为千位分隔符。下面是将数据写入 Excel 文件的控制台应用程序。
Make sure you have referenced Microsoft.Office.Interop.Excel dll
确保您已引用 Microsoft.Office.Interop.Excel dll
using System.Collections.Generic;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var bankAccounts = new List<Account> {
new Account { ID = 345678, Balance = 541.27},
new Account {ID = 1230221,Balance = -1237.44},
new Account {ID = 346777,Balance = 3532574},
new Account {ID = 235788,Balance = 1500.033333}
};
DisplayInExcel(bankAccounts);
}
static void DisplayInExcel(IEnumerable<Account> accounts)
{
var excelApp = new Excel.Application { Visible = true };
excelApp.Workbooks.Add();
Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
workSheet.Cells[1, "A"] = "ID Number";
workSheet.Cells[1, "B"] = "Current Balance";
var row = 1;
foreach (var acct in accounts)
{
row++;
workSheet.Cells[row, "A"] = acct.ID;
workSheet.Cells[row, "B"] = acct.Balance;
}
workSheet.Range["B2", "B" + row].NumberFormat = "#,###.00 ";
workSheet.Columns[1].AutoFit();
workSheet.Columns[2].AutoFit();
}
}
public class Account
{
public int ID { get; set; }
public double Balance { get; set; }
}
}
The Output
输出