0

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

我的代码:

  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

在上面,"Bathroom Fitter, Plumbing: 100"在第 3 列中包含 a,但它将整个字符串保留在一个 excel 字段中。当谈到最后一列时, FitterPlumbing之间的字符串中"Bathroom Fitter Plumbing: 112"有 a ,所以现在发生的是 this ,被视为分隔符,因此在 excel 中将其拆分为两个单元格,因此我在一个单元格和下一个。整个字符串应该在一个单元格中。它只在最后一列这样做?请帮我纠正这个。,Bathroom FitterPlumbing:112

谢谢

4

2 回答 2

1

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

“浴室装配工,水暖:100”,下一栏,“带逗号的栏”。

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

...Append(item.Week2).Append("\",\"").Append(item.Week1).Append("\"").Append(Environment.NewLine);
于 2012-08-24T07:30:00.690 回答
0

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

于 2012-08-24T07:29:09.967 回答