将Excel工作表另存为CSV,并以空格和分号作为分隔符

我在C#中导出一个Excel.Worksheet,如下所示:

myWorksheet.SaveAs(myPath, Excel.XlFileFormat.xlCSV); 

它几乎可以工作,但我需要强制两件事情:

  • “字段分隔符”应该是分号(;)。 我得到一个逗号(,)
  • “文本分隔符”应始终为空。 我得到双引号(“”)

该文件是完全无益的(到底是什么“xlTextWindows:指定一种文本格式”应该是什么意思?)

任何想法?

用分号replace逗号的VBA(不是C#)解决scheme是:

 Sub CreateCSV() Dim rCell As Range Dim rRow As Range Dim sOutput As String Dim sFname As String, lFnum As Long 'Open a text file to write sFname = "C:\MyCsv.csv" lFnum = FreeFile Open sFname For Output As lFnum 'Loop through the rows' For Each rRow In ActiveSheet.UsedRange.Rows 'Loop through the cells in the rows' For Each rCell In rRow.Cells sOutput = sOutput & rCell.Value & ";" Next rCell 'remove the last comma' sOutput = Left(sOutput, Len(sOutput) - 1) 'write to the file and reinitialize the variables' Print #lFnum, sOutput sOutput = "" Next rRow 'Close the file' Close lFnum End Sub 

源testing和工作。 现在,我不确定你说的是什么文字分隔符,但我没有遇到过。 如果你使用VBA的方式,让我知道如果这仍然发生,我们将改变代码。 如果这个VBA解决scheme对你完全没用,我很抱歉!

谢谢你们,但是我正在寻找一些不那么笨拙的东西。

无论如何,因为我离closures项目只有一步之遥,所以我把这样一个不起眼的工作解决scheme放在一起:

 static public void WorksheetToCSV(Excel.Worksheet origine, string CSVoutPath, string fieldSeparator, string textSeparator) { Excel.Range rngCurrentRow; string lineaDaScrivere; TextWriter csv = new StreamWriter(CSVoutPath); for (int i = 1; i <= origine.UsedRange.Rows.Count; i++) { rngCurrentRow = origine.UsedRange.get_Range("A" + i, "A" + i).EntireRow; lineaDaScrivere=""; foreach (Excel.Range cella in rngCurrentRow.Columns) { try { lineaDaScrivere = lineaDaScrivere + textSeparator + cella.Value.ToString() + textSeparator + fieldSeparator; } catch (NullReferenceException ex) { break; } } lineaDaScrivere=lineaDaScrivere.Substring(0, (lineaDaScrivere.Length - fieldSeparator.Length)); csv.WriteLine(lineaDaScrivere); } csv.Close(); } 

有更好的解决scheme,但是这个工作正如我所料。