gpt4 book ai didi

c# - 格式化 Excel 单元格(货币)

转载 作者:IT王子 更新时间:2023-10-29 04:49:52 28 4
gpt4 key购买 nike

我为 Excel 开发了一个加载项,因此您可以将 MySQL 数据库中的一些数字插入到特定的单元格中。现在我试图将这些单元格格式化为货币,但我遇到了两个问题。1. 在带格式的单元格上使用公式时,总和显示如下:“353,2574 欧元”。我该怎么做才能以适当的方式显示它?2. 有些单元格是空的,但也必须以货币格式设置。当使用我用于求和公式的相同格式并输入内容时,只显示数字。没有“€”,什么都没有。那是什么?我指定了一个 Excel.Range 并用它来格式化范围

sum.NumberFormat = "#.## €";

不过我也试过了

sum.NumberFormat = "0,00 €";
sum.NumberFormat = "#.##0,00 €";

有人知道吗?

最佳答案

这个对我有用。我有 excel 测试应用程序,它将货币格式设置为小数点后 2 位,并以逗号作为千位分隔符。下面是将数据写入 Excel 文件的控制台应用程序。

确保您已引用 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; }
}
}

输出

enter image description here

关于c# - 格式化 Excel 单元格(货币),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14338156/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com