我在C#中导出Excel.Worksheet,如下所示:
myWorksheet.SaveAs(myPath, Excel.XlFileFormat.xlCSV);
它几乎没问题,但我需要强制做两件事:
The documentation完全没有用(什么是“xlTextWindows:指定一种文本格式。”应该是什么意思?)
有什么想法吗?
答案 0 :(得分:1)
用分号替换逗号的VBA(而不是C#)解决方案是:
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
source测试并运作。现在,我不确定你所说的""
是什么文字分隔符,但我还没有遇到过。如果你采用VBA方式,请告诉我这是否仍在发生,我们将改变代码。如果这个VBA解决方案对你来说完全没用,我道歉!
答案 1 :(得分:1)
谢谢你们,但我一直在寻找一些不那么笨拙的东西。
无论如何,由于我距离关闭项目只有一步之遥,因此我将这样一个不优雅但工作正常的解决方案放在一起:
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();
}
有更好的解决方案,但这对我有用。