65.9K
CodeProject 正在变化。 阅读更多。
Home

将Excel文件导入DataSet

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.69/5 (23投票s)

2009 年 1 月 9 日

CPOL
viewsIcon

350447

downloadIcon

12546

允许将 Excel 表格导入到 DataSet 中。

引言

我只是想提供两种将数据从 Excel 导入到 DataSet 的方法。

  1. 首选 - 使用 OLE Jet 引擎从 XLS 文件导入(简单)。
    1. 更新:我现在将 IMEX 标志设置为 0。这可能会导致性能下降。请查看 http://www.connectionstrings.com/excel 以获取更多信息。
    2. 更新:如果文件扩展名为 XLSX,则我将其切换为使用 ACE 驱动程序。您需要确保 ACE 安装在您部署到的服务器上。
      1. http://www.microsoft.com/en-us/download/details.aspx?id=13255 
    3. 更新:请参考以下链接,获取有关连接到 xls 和 xlsx 文件的良好信息:
      1. http://www.connectionstrings.com/excel
      2. http://www.connectionstrings.com/excel-2007  
  2. 从 Excel XML 文件导入。(Excel 使用的 XML 格式,而不仅仅是任何 XML 文件。)
    1. 注意:这是一个冗长的自定义解决方案。应该可以工作,但可能需要调整。
    2. 如果确定数据有效,或者不需要进行类型检测(在过程中为此标志),则此方法效果很好。
    3. 将数据导出到 Excel XML 文件可以在这里找到

使用代码

下载文件以获取具体信息,但这里有一个摘要

XLS 导入

public static DataSet ImportExcelXLS(string FileName, bool hasHeaders) {
    string HDR = hasHeaders ? "Yes" : "No";
    string strConn;
    if (FileName.Substring(FileName.LastIndexOf('.')).ToLower() == ".xlsx")
        strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
    else
        strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";

    DataSet output = new DataSet();

    using (OleDbConnection conn = new OleDbConnection(strConn)) {
        conn.Open();

        DataTable schemaTable = conn.GetOleDbSchemaTable(
            OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

        foreach (DataRow schemaRow in schemaTable.Rows) {
            string sheet = schemaRow["TABLE_NAME"].ToString();

            if (!sheet.EndsWith("_")) {
                try {
                    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
                    cmd.CommandType = CommandType.Text;

                    DataTable outputTable = new DataTable(sheet);
                    output.Tables.Add(outputTable);
                    new OleDbDataAdapter(cmd).Fill(outputTable);
                } catch (Exception ex) {
                    throw new Exception(ex.Message + string.Format("Sheet:{0}.File:F{1}", sheet, FileName), ex);
                }
            }
        }
    }
    return output;
} 

Excel XML 导入(摘要)

public static DataSet ImportExcelXML(Stream inputFileStream, 
                      bool hasHeaders, bool autoDetectColumnType) {
    XmlDocument doc = new XmlDocument();
    doc.Load(new XmlTextReader(inputFileStream));
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

    nsmgr.AddNamespace("o", "urn:schemas-microsoft-com:office:office");
    nsmgr.AddNamespace("x", "urn:schemas-microsoft-com:office:excel");
    nsmgr.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");

    DataSet ds = new DataSet();

    foreach (XmlNode node in 
      doc.DocumentElement.SelectNodes("//ss:Worksheet", nsmgr)) {
        DataTable dt = new DataTable(node.Attributes["ss:Name"].Value);
        ds.Tables.Add(dt);
        XmlNodeList rows = node.SelectNodes("ss:Table/ss:Row", nsmgr);
        if (rows.Count > 0) {

            //*************************
            //Add Columns To Table from header row
            //*************************
            List<ColumnType> columns = new List<ColumnType>();
            int startIndex = 0;
            if (hasHeaders) {
                foreach (XmlNode data in rows[0].SelectNodes("ss:Cell/ss:Data", nsmgr)) {
                    columns.Add(new ColumnType(typeof(string)));//default to text
                    dt.Columns.Add(data.InnerText, typeof(string));
                }
                startIndex++;
            }
            //*************************
            //Update Data-Types of columns if Auto-Detecting
            //*************************
            if (autoDetectColumnType && rows.Count > 0) {
                XmlNodeList cells = rows[startIndex].SelectNodes("ss:Cell", nsmgr);
                int actualCellIndex = 0;
                for (int cellIndex = 0; cellIndex < cells.Count; cellIndex++) {
                    XmlNode cell = cells[cellIndex];
                    if (cell.Attributes["ss:Index"] != null)
                        actualCellIndex = 
                          int.Parse(cell.Attributes["ss:Index"].Value) - 1;

                    ColumnType autoDetectType = 
                      getType(cell.SelectSingleNode("ss:Data", nsmgr));

                    if (actualCellIndex >= dt.Columns.Count) {
                        dt.Columns.Add("Column" + 
                          actualCellIndex.ToString(), autoDetectType.type);
                        columns.Add(autoDetectType);
                    } else {
                        dt.Columns[actualCellIndex].DataType = autoDetectType.type;
                        columns[actualCellIndex] = autoDetectType;
                    }

                    actualCellIndex++;
                }
            }
            //*************************
            //Load Data
            //*************************
            for (int i = startIndex; i < rows.Count; i++) {
                DataRow row = dt.NewRow();
                XmlNodeList cells = rows[i].SelectNodes("ss:Cell", nsmgr);
                int actualCellIndex = 0;
                for (int cellIndex = 0; cellIndex < cells.Count; cellIndex++) {
                    XmlNode cell = cells[cellIndex];
                    if (cell.Attributes["ss:Index"] != null)
                        actualCellIndex = int.Parse(cell.Attributes["ss:Index"].Value) - 1;

                    XmlNode data = cell.SelectSingleNode("ss:Data", nsmgr);

                    if (actualCellIndex >= dt.Columns.Count) {
                        for (int i = dt.Columns.Count; i < actualCellIndex; i++) {
                            dt.Columns.Add("Column" + 
                                       actualCellIndex.ToString(), typeof(string));
                            columns.Add(getDefaultType());
                        }
                        ColumnType autoDetectType = 
                           getType(cell.SelectSingleNode("ss:Data", nsmgr));
                        dt.Columns.Add("Column" + actualCellIndex.ToString(), 
                                       typeof(string));
                        columns.Add(autoDetectType);
                    }
                    if (data != null)
                        row[actualCellIndex] = data.InnerText;

                    actualCellIndex++;
                }

                dt.Rows.Add(row);
            }
        }
    }
    return ds;
}
    //*************************
    //Format of file, in case you're wondering
    //*************************

    //<?xml version="1.0"?>
    //<?mso-application progid="Excel.Sheet"?>
    //<Workbook>
    // <Worksheet ss:Name="Sheet1">
    //  <Table>
    //   <Row>
    //    <Cell><Data ss:Type="String">Item Number</Data></Cell>
    //    <Cell><Data ss:Type="String">Description</Data></Cell>
    //    <Cell ss:StyleID="s21"><Data ss:Type="String">Item Barcode</Data></Cell>
    //   </Row>
    // </Worksheet>
    //</Workbook>
© . All rights reserved.