我正在从 Datatable 编写 csv 文件。在下面检查我的代码
public static void SaveDataTableToCsvFile(string AbsolutePathAndFileName, DataTable TheDataTable, params string[] Options)
{
//variables
string separator;
if (Options.Length > 0)
{
separator = Options[0];
}
else
{
separator = ""; //default
}
string quote = "";
FileInfo info = new FileInfo(AbsolutePathAndFileName);
if (IsFileLocked(info))
{
MessageBox.Show("File is in use, please close the file");
return;
}
//create CSV file
StreamWriter sw = new StreamWriter(AbsolutePathAndFileName);
//write header line
int iColCount = TheDataTable.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(TheDataTable.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(separator);
}
}
sw.Write(sw.NewLine);
//write rows
foreach (DataRow dr in TheDataTable.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string data = dr[i].ToString();
data = data.Replace("\"", "\\\"").Replace(",", " ");
sw.Write(quote + data + quote);
}
if (i < iColCount - 1)
{
sw.Write(separator);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
代码对我有用,但我需要在 csv 的某些单元格中添加颜色代码。
我怎样才能做到这一点 ?