【发布时间】:2011-08-26 18:14:46
【问题描述】:
我需要将 Excel (2010) 文件转换为 csv。目前我正在使用 Excel Interop 打开和 SaveAs csv,效果很好。但是 Interop 在我们使用它的环境中存在一些问题,所以我正在寻找另一种解决方案。
我发现在没有互操作的情况下使用 Excel 文件的方法是使用 OpenXML SDK。我收集了一些代码来遍历每张工作表中的所有单元格,然后将它们简单地写入另一个 CSV 文件。
我遇到的一个问题是处理空白行和单元格。看来,使用此代码,空白行和单元格完全不存在,因此我无法了解它们。是否可以遍历所有行和单元格,包括空白?
string filename = @"D:\test.xlsx";
string outputDir = Path.GetDirectoryName(filename);
//--------------------------------------------------------
using (SpreadsheetDocument document = SpreadsheetDocument.Open(filename, false))
{
foreach (Sheet sheet in document.WorkbookPart.Workbook.Descendants<Sheet>())
{
WorksheetPart worksheetPart = (WorksheetPart) document.WorkbookPart.GetPartById(sheet.Id);
Worksheet worksheet = worksheetPart.Worksheet;
SharedStringTablePart shareStringPart = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
SharedStringItem[] items = shareStringPart.SharedStringTable.Elements<SharedStringItem>().ToArray();
// Create a new filename and save this file out.
if (string.IsNullOrWhiteSpace(outputDir))
outputDir = Path.GetDirectoryName(filename);
string newFilename = string.Format("{0}_{1}.csv", Path.GetFileNameWithoutExtension(filename), sheet.Name);
newFilename = Path.Combine(outputDir, newFilename);
using (var outputFile = File.CreateText(newFilename))
{
foreach (var row in worksheet.Descendants<Row>())
{
StringBuilder sb = new StringBuilder();
foreach (Cell cell in row)
{
string value = string.Empty;
if (cell.CellValue != null)
{
// If the content of the first cell is stored as a shared string, get the text
// from the SharedStringTablePart. Otherwise, use the string value of the cell.
if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
value = items[int.Parse(cell.CellValue.Text)].InnerText;
else
value = cell.CellValue.Text;
}
// to be safe, always use double quotes.
sb.Append(string.Format("\"{0}\",", value.Trim()));
}
outputFile.WriteLine(sb.ToString().TrimEnd(','));
}
}
}
}
如果我有以下 Excel 文件数据:
one,two,three
,,
last,,row
我会得到以下 CSV(这是错误的):
one,two,three
last,row
【问题讨论】:
-
此 OpenXML code example 来自 MS 文档 Just Works。 @user6748024 下面的示例并未涵盖所有数据类型或使用 InnerText,您必须这样做。
标签: c# .net excel openxml openxml-sdk