【问题标题】:How do you convert Excel to CSV using OpenXML SDK?如何使用 OpenXML SDK 将 Excel 转换为 CSV?
【发布时间】: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


【解决方案1】:
//Xlsx to Csv
ConvertXlsxToCsv(@"D:\test.xlsx", @"C:\");

internal static void ConvertXlsxToCsv(string SourceXlsxName, string DestinationCsvDirectory)
{
    try
    {
        using (SpreadsheetDocument document = SpreadsheetDocument.Open(SourceXlsxName, false))
        {

            foreach (Sheet _Sheet in document.WorkbookPart.Workbook.Descendants<Sheet>())
            {
                WorksheetPart _WorksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(_Sheet.Id);
                Worksheet _Worksheet = _WorksheetPart.Worksheet;

                SharedStringTablePart _SharedStringTablePart = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
                SharedStringItem[] _SharedStringItem = _SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ToArray();

                if (string.IsNullOrEmpty(DestinationCsvDirectory))
                    DestinationCsvDirectory = Path.GetDirectoryName(SourceXlsxName);
                string newFilename = string.Format("{0}_{1}.csv", Path.GetFileNameWithoutExtension(SourceXlsxName), _Sheet.Name);
                newFilename = Path.Combine(DestinationCsvDirectory, newFilename);

                using (var outputFile = File.CreateText(newFilename))
                {
                    foreach (var row in _Worksheet.Descendants<Row>())
                    {
                        StringBuilder _StringBuilder = new StringBuilder();
                        foreach (Cell _Cell in row)
                        {
                            string Value = string.Empty;
                            if (_Cell.CellValue != null)
                            {
                                if (_Cell.DataType != null && _Cell.DataType.Value == CellValues.SharedString)
                                    Value = _SharedStringItem[int.Parse(_Cell.CellValue.Text)].InnerText;
                                else
                                    Value = _Cell.CellValue.Text;
                            }
                            _StringBuilder.Append(string.Format("{0},", Value.Trim()));
                        }
                        outputFile.WriteLine(_StringBuilder.ToString().TrimEnd(','));
                    }
                }
            }
        }
    }
    catch (Exception Ex)
    {
        throw Ex;
    }
}

【讨论】:

  • 我不知道为什么这个答案不在顶部。最可靠、最新,无需安装驱动程序,也无需与邪恶的基础设施人员交谈。
  • 这段代码读取大文件可能会导致 OutOfMemoryException 原因是将整个 excel 读入内存。要对其进行缩放,它应该改用 OpenXmlReader。请看一下这个链接:docs.microsoft.com/en-us/office/open-xml/…
  • 这有很多错误:它不支持值中的“,”值(不能正确编码 CSV)并且它不支持正确地连续丢失单元格
【解决方案2】:

我不认为 OpenXml 是解决这个问题的正确工具。我建议将数据从工作表 with an OleDbConnection 中取出,然后使用 this 方法放入 csv 文件中。

一旦您在内存中的数据表中获取数据,您就可以更好地控制情况。

【讨论】:

  • OleDbConnection 不需要安装 Excel 吗? Open XML SDK 的优点是不需要 Excel。
  • 不,不需要。它将文件视为二进制数据存储,它就是这样。出于某种原因,我大约每两到三年就会这样做一次:)。
  • 我还应该注意,我做了很多 OpenXml 工作......这将是一个使用核武器杀死蚊子的案例。
  • @Philipp 我同意克里斯的观点。我已经这样做了好几次,并且总是只使用 OleDbConnection。您不需要 excel,只需要正确的 .net 框架。
  • @Chris 这可能不需要安装 Excel,但看起来必须安装 OLEDB 提供程序。这是我需要作为应用程序的先决条件安装的东西吗?
【解决方案3】:

您可以使用 oledb 连接查询 excel 文件,将行转换为 csv 格式并将结果保存到文件中

这是我为此测试的一个简单示例 它创建一个不同的 csv 文件 unicode 编码,为 excel 文件中的每个工作表分隔制表符

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;

namespace XlsTests
{
    class Program
    {
        static void Main(string[] args)
        {
            string _XlsConnectionStringFormat = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=NO;IMEX=1\"";
            string xlsFilename = @"C:\test.xlsx";
            using (OleDbConnection conn = new OleDbConnection(string.Format(_XlsConnectionStringFormat, xlsFilename)))
            {
                try
                {
                    conn.Open();

                    string outputFilenameHeade = Path.GetFileNameWithoutExtension(xlsFilename);
                    string dir = Path.GetDirectoryName(xlsFilename);
                    string[] sheetNames = conn.GetSchema("Tables")
                                              .AsEnumerable()
                                              .Select(a => a["TABLE_NAME"].ToString())
                                              .ToArray();
                    foreach (string sheetName in sheetNames)
                    {
                        string outputFilename = Path.Combine(dir, string.Format("{0}_{1}.csv", outputFilenameHeade, sheetName));
                        using (StreamWriter sw = new StreamWriter(File.Create(outputFilename), Encoding.Unicode))
                        {
                            using (DataSet ds = new DataSet())
                            {
                                using (OleDbDataAdapter adapter = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", sheetName), conn))
                                {
                                    adapter.Fill(ds);

                                    foreach (DataRow dr in ds.Tables[0].Rows)
                                    {
                                        string[] cells = dr.ItemArray.Select(a => a.ToString()).ToArray();
                                        sw.WriteLine("\"{0}\"", string.Join("\"\t\"", cells));
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception exp)
                {
                    // handle exception
                }
                finally
                {
                    if (conn.State != ConnectionState.Open)
                    {
                        try
                        {
                            conn.Close();
                        }
                        catch (Exception ex)
                        {
                            // handle exception
                        }
                    }
                }
            }
        }
    }
}

【讨论】:

  • 感谢@Adam,但此代码不会写出 excel 文件的第一行。我猜它被视为列名?这不是我想要的。知道有什么方法可以避免吗?
猜你喜欢
  • 2012-04-24
  • 2012-02-03
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-19
  • 2012-10-10
  • 2016-11-30
相关资源
最近更新 更多