使用逗号分隔的问题将数据导出到C#中的Excel

时间:2012-08-24 07:16:47

标签: c# excel

问题不在于导出本身,而是如何用逗号分隔字段,我在字段中有逗号。一切正常,直到它到达字符串包含逗号的最后一个字段,它将其分隔

我的代码:

  foreach (var item in jobSortedReportData)
  {
       sb.Append("\"").Append(item.Title).Append("\",\"").Append(item.Total).Append("\",\"").Append(item.Week6).Append("\",\"").Append(item.Week5).Append("\",\"").Append(item.Week4).Append("\",\"").Append(item.Week3).Append("\",\"").Append(item.Week2).Append("\",").Append(item.Week1).Append(Environment.NewLine);                     
  }

  byte[] textBytes2 = Encoding.UTF8.GetBytes(sb.ToString());

这会产生的输出:

 Number 1 Job Search    0   **Bathroom Fitter, Plumbing: 100**  Carpenter, Joinery: 99  Carpenter, Joinery: 81  Carpenter, Joinery: 209 Electrician, Domestic Electrical: 495   **Bathroom Fitter    Plumbing: 112**
 Number 2 Job Search    0   Carpenter, Joinery: 97  Bathroom Fitter, Plumbing: 99   Bathroom Fitter, Plumbing: 79   Bathroom Fitter, Plumbing: 150  Bathroom Fitter, Plumbing: 453  Builder  Window Installation: 75
 Number 3 Job Search    0   Builder, Window Installation: 85    Building Contractor, Kitchen Fitting: 97    Plumber, Bathroom Fitting: 51   Builder, Window Installation: 134   Heating Engineer, Gas Installation: 451 Bathroom Fitter  Bathroom Fitting: 74

原始视图:

"Number 3 Job Search","0","Builder, Window Installation: 85","Building Contractor, Kitchen     Fitting: 97","Plumber, Bathroom Fitting: 51","Builder, Window Installation: 134","Heating Engineer, Gas Installation: 451",Bathroom Fitter, Bathroom Fitting: 74 
"Number 1 Tradesmen Search","0","Painter & Decorator: 316","Painter & Decorator: 229","Painter & Decorator: 146","Builder: 324","TV Aerials & In-home Entertainment Installer: 1378",Electrician: 247 
"Number 2 Tradesmen Search","0","Builder: 171","Builder: 191","Plumber: 114","Plumber: 295","Builder: 551",Builder: 205 
"Number 3 Tradesmen Search","0","Plumber: 123","Plumber: 160","Builder: 108","Painter & Decorator: 231","Domestic Electrical: 495",Painter & Decorator: 160

在上文中,第3列中的"Bathroom Fitter, Plumbing: 100"包含,,但它将整个字符串保存在一个excel字段中。当谈到最后一列"Bathroom Fitter Plumbing: 112"时, Fitter Plumbing 之间的字符串中有一个,,所以现在发生的是这个,是看作是一个分隔符,所以在excel中将它拆分为 TWO 单元格,因此我在一个单元格中有Bathroom Fitter,在下一个单元格中有Plumbing:112。整个字符串应该在一个单元格中。它仅在最后一列上执行此操作?请帮我纠正一下。

由于

2 个答案:

答案 0 :(得分:1)

很难看出原始csv,但记得如果CSV字段包含逗号以防止它认为它是一个列,则需要使用文本限定符。因此,原始CSV应如下所示,以获得一致的结果:

“浴室钳工,管道:100”,下一栏,“带逗号的栏目”。

编辑:现在我已经看到原始代码不应该在最后看起来像这样吗?我不认为你在最后一个字段添加文本限定符:

...Append(item.Week2).Append("\",\"").Append(item.Week1).Append("\"").Append(Environment.NewLine);

答案 1 :(得分:0)

CSV输出是每个人似乎都在自己推出的东西之一,但后来不可避免地发现他们忘记了某些情况,并希望他们只是抓住了一个库来为他们做。我使用的是CsvHelper(https://github.com/JoshClose/CsvHelper)。我相信这是一个非常普遍的解决方案。