如何在 C# 中使用 StringBuilder 强制 CSV 列将数字视为文本
How to force a CSV column to treat numbers as text, in C# using StringBuilder
我有一个 C# 程序正在从 RESTful API 中读取数据并将其输出到 CSV 文件中。
if (response.IsSuccessful)
{
//serialize the data into the Devices[] array RootObject
RootObject ro = new RootObject();
ro = JsonConvert.DeserializeObject<RootObject>(response.Content);
//create a new DataTable with columns specifically required
DataTable dt = new DataTable("tblDevices");
dt.Columns.Add("AssetNumber");
dt.Columns.Add("DeviceFriendlyName");
dt.Columns.Add("IMEI");
//iterate through each device data and add it into a DataRow
foreach(Device d in ro.Devices)
{
DataRow dr = dt.NewRow();
dr["AssetNumber"] = d.AssetNumber;
dr["DeviceFriendlyName"] = d.DeviceFriendlyName;
dr["IMEI"] = '"'+d.Imei+'"'; //<-- this is always a "number" in CSV
和 stringbuilder 代码:
//now turn the datatable into a enumerated string
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
//read each row of the datateble, enumrate and save into the StringBuilder object
foreach (DataRow row in dt.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
//finally save the string as a CSV file
string FilePath = ConfigurationManager.AppSettings["FilePath"];
string wsFileName = FilePath+"\airwatch_"+DateTime.Now.ToString("yyyyMMddHHmm")+".csv";
File.WriteAllText(wsFileName, sb.ToString());
当我打开 CSV 时,我得到的 IMEI 号码总是 Excel 中的一个号码。
所以它没有将数字显示为字符串 - “353034999819999”,而是显示为“3.53034E+14”。是的,这是一个很大的数字。
我不希望它作为指数。我想要的是 Excel.
中的字符串
我试过在字段周围加双引号,如上代码所示,它始终作为数字传递。我也尝试过在值的开头使用单引号,但它看起来像一个开头带有单引号的字符串。
如何将此值作为字符串而不是数字保存在 CSV 文件中?
在 excel 上将该列格式化为数字:
如果你不想这样做,那么你可以试试这个代码:
// make sure you use the CsvHelper nuget package.
using CsvHelper;
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main(string[] args)
{
var recordsToSave = new List<Foo>();
recordsToSave.Add(new Foo()
{
LargeNumber = "=\"353034999819999\"",
Name = "SomeName"
});
var fileStream = new FileStream("output.csv", FileMode.CreateNew);
using StreamWriter writer = new StreamWriter(fileStream);
using var csv = new CsvWriter(writer);
csv.WriteRecords(recordsToSave);
}
class Foo
{
public string Name { get; set; }
public string LargeNumber { get; set; }
}
}
您好,如果对您有帮助的话,我有一个 DataGridView
,其中的列看起来像“8940012004412026012”。为了导出到 CVS,我使用:
if (rap_cuiclient.Rows.Count > 0)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV (*.csv)|*.csv";
sfd.FileName = "Output.csv";
bool fileError = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
if (File.Exists(sfd.FileName))
{
try
{
File.Delete(sfd.FileName);
}
catch (IOException ex)
{
fileError = true;
MessageBox.Show("Tabelul este gol" + ex.Message);
}
}
if (!fileError)
{
try
{
int columnCount = rap_cuiclient.Columns.Count;
string columnNames = "";
string[] outputCsv = new string[rap_cuiclient.Rows.Count + 1];
for (int i = 0; i < columnCount; i++)
{
columnNames += rap_cuiclient.Columns[i].HeaderText.ToString() + ",";
}
outputCsv[0] += columnNames;
for (int i = 1; (i - 1) < rap_cuiclient.Rows.Count; i++)
{
for (int j = 0; j < columnCount; j++)
{
outputCsv[i] += rap_cuiclient.Rows[i - 1].Cells[j].Value.ToString() + ",";
}
}
File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);
MessageBox.Show("Datele au fost exportate cu scucces !!!", "Info");
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message);
}
}
}
}
else
{
MessageBox.Show("Nu sunt date pentru export !!!", "Info");
}
这是结果
我有一个 C# 程序正在从 RESTful API 中读取数据并将其输出到 CSV 文件中。
if (response.IsSuccessful)
{
//serialize the data into the Devices[] array RootObject
RootObject ro = new RootObject();
ro = JsonConvert.DeserializeObject<RootObject>(response.Content);
//create a new DataTable with columns specifically required
DataTable dt = new DataTable("tblDevices");
dt.Columns.Add("AssetNumber");
dt.Columns.Add("DeviceFriendlyName");
dt.Columns.Add("IMEI");
//iterate through each device data and add it into a DataRow
foreach(Device d in ro.Devices)
{
DataRow dr = dt.NewRow();
dr["AssetNumber"] = d.AssetNumber;
dr["DeviceFriendlyName"] = d.DeviceFriendlyName;
dr["IMEI"] = '"'+d.Imei+'"'; //<-- this is always a "number" in CSV
和 stringbuilder 代码:
//now turn the datatable into a enumerated string
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
//read each row of the datateble, enumrate and save into the StringBuilder object
foreach (DataRow row in dt.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
//finally save the string as a CSV file
string FilePath = ConfigurationManager.AppSettings["FilePath"];
string wsFileName = FilePath+"\airwatch_"+DateTime.Now.ToString("yyyyMMddHHmm")+".csv";
File.WriteAllText(wsFileName, sb.ToString());
当我打开 CSV 时,我得到的 IMEI 号码总是 Excel 中的一个号码。
所以它没有将数字显示为字符串 - “353034999819999”,而是显示为“3.53034E+14”。是的,这是一个很大的数字。
我不希望它作为指数。我想要的是 Excel.
中的字符串我试过在字段周围加双引号,如上代码所示,它始终作为数字传递。我也尝试过在值的开头使用单引号,但它看起来像一个开头带有单引号的字符串。
如何将此值作为字符串而不是数字保存在 CSV 文件中?
在 excel 上将该列格式化为数字:
如果你不想这样做,那么你可以试试这个代码:
// make sure you use the CsvHelper nuget package.
using CsvHelper;
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main(string[] args)
{
var recordsToSave = new List<Foo>();
recordsToSave.Add(new Foo()
{
LargeNumber = "=\"353034999819999\"",
Name = "SomeName"
});
var fileStream = new FileStream("output.csv", FileMode.CreateNew);
using StreamWriter writer = new StreamWriter(fileStream);
using var csv = new CsvWriter(writer);
csv.WriteRecords(recordsToSave);
}
class Foo
{
public string Name { get; set; }
public string LargeNumber { get; set; }
}
}
您好,如果对您有帮助的话,我有一个 DataGridView
,其中的列看起来像“8940012004412026012”。为了导出到 CVS,我使用:
if (rap_cuiclient.Rows.Count > 0)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV (*.csv)|*.csv";
sfd.FileName = "Output.csv";
bool fileError = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
if (File.Exists(sfd.FileName))
{
try
{
File.Delete(sfd.FileName);
}
catch (IOException ex)
{
fileError = true;
MessageBox.Show("Tabelul este gol" + ex.Message);
}
}
if (!fileError)
{
try
{
int columnCount = rap_cuiclient.Columns.Count;
string columnNames = "";
string[] outputCsv = new string[rap_cuiclient.Rows.Count + 1];
for (int i = 0; i < columnCount; i++)
{
columnNames += rap_cuiclient.Columns[i].HeaderText.ToString() + ",";
}
outputCsv[0] += columnNames;
for (int i = 1; (i - 1) < rap_cuiclient.Rows.Count; i++)
{
for (int j = 0; j < columnCount; j++)
{
outputCsv[i] += rap_cuiclient.Rows[i - 1].Cells[j].Value.ToString() + ",";
}
}
File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);
MessageBox.Show("Datele au fost exportate cu scucces !!!", "Info");
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message);
}
}
}
}
else
{
MessageBox.Show("Nu sunt date pentru export !!!", "Info");
}
这是结果