[英]How to use the correct Decimal separator and Thousands separator when exporting to excel in c#?
[英]How to change separator for decimal and thousands in numbers in Excel C #?
我正在尝试在 C # 中编写一个程序来更改 Excel 文件中找到的数字的格式
1234,456 在 1,234.456;
23456,3 乘 23,456.3;
5,243.345 中的 5243,345 等。
foreach (Excel.Worksheet sheet in exDocument.Worksheets) {
Excel.Range last = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = sheet.get_Range("A1", last);
int lastUsedRow = last.Row;
int lastUsedColumn = last.Column;
for (int rowIndex = 1; rowIndex <= lastUsedColumn; rowIndex++) {
for (int columnIndex = 1; columnIndex <= lastUsedRow; columnIndex++) {
if (range.Cells[columnIndex, rowIndex].value2 != null) {
string myString = ((Excel.Range)sheet.Cells[columnIndex, rowIndex]).Value2.ToString();
range.Cells[columnIndex, rowIndex] = FormatNumber(myString);
Console.WriteLine(range.Cells[columnIndex, rowIndex]);
// object missingVal = System.Reflection.Missing.Value;
// Excel.Range match = range.Cells[columnIndex, rowIndex].Value2.ToString().Find("<[0-9]@,[0-9]@>", missingVal, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,
// Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, missingVal, missingVal);
//strok.Find.text= "<[0-9]@,[0-9]@>";
}
}
}
}
private static string FormatNumber(string text) {
if (double.TryParse(text, out double number)) {
return number.ToString("N", CultureInfo.CreateSpecificCulture("en-US"));
// Console.WriteLine(number);
}
return text;
}
数字没有改变,在控制台中我看到了。
System.__ComObject
System.__ComObject
System.__ComObject
System.__ComObject
System.__ComObject
System.__ComObject
System.__ComObject
System.__ComObject
System.__ComObject
请告诉我如何正确地将找到的数字转换为所需的格式。
在您的情况下,此方法可以工作。
private static string FormatNumber(string text)
{
text= text.Replace(',', '.');
double number;
if (double.TryParse(text, out number))
{
string result = String.Format("{0:N}", number);
return result;
}
return text;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.