C#使用OpenXml.Spreadsheet填充DataGrid

时间:2018-05-09 20:40:03

标签: c# datatable openxml

我想使用OpenXml.Spreadsheet引用使用speadsheet中的值填充DataTable。不幸的是,我的方法效果不佳。我得到的对象引用没有设置为对象错误的实例。你能就最好的行动方案提出建议吗?看起来像myCollection.Add(文本)似乎打破了它。

using DocumentFormat.OpenXml.Spreadsheet;


public DataTable ReadXls(string filePath)
    {       
        // create a new datatable

        DataTable xlsData = new DataTable();
        DataTable xlsDataOut = new DataTable();

        try
        {
            using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filePath, true))
            {
                // invoke spreadsheet stuff

                WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
                WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
                SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();

                // determine number of rows/columns to create DataTable

                foreach (Column col in sheetData.Elements<Column>())
                {
                    DataColumn serialno = new DataColumn();
                    serialno.AllowDBNull = true;
                    xlsData.Columns.Add(serialno);
                }

                foreach (Row r in sheetData.Elements<Row>())
                {
                    DataRow dtRow = xlsData.NewRow();
                    xlsData.Rows.Add(dtRow);
                }

                // column and row count for dataset
                int colcount = xlsData.Columns.Count;
                int rowcount = xlsData.Rows.Count;

                // invoke individual cell 

                foreach (Row r in sheetData.Elements<Row>())
                {
                    List<string> myCollection = new List<string>();
                    DataRow dr = xlsDataOut.NewRow();

                    foreach (Cell c in r.Elements<Cell>())
                    {
                        string text = c.CellValue.Text;
                        myCollection.Add(text);
                    }

                    for (int i = 0; i < colcount; i++)
                    {
                        dr[i] = myCollection[i];
                    }

                    xlsDataOut.Rows.Add(dr);
                }
            }
        }

        catch (Exception ex)
        {
            MessageBox.Show("Error creating DataTable from xls file" + "\n" + ex.Message + "\n" + ex.StackTrace);
        }

        return xlsDataOut;
    }

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,这很有效。特别感谢来自Experts Exchange的it_Saige。

public void btnOpenExcel_Click(object sender, EventArgs e)
    {
        // Upload data from .xls file
        try
        {
            // Pulls up file reader

            using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "xlsx|*.xlsx", ValidateNames = true })
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    lblFileName.Text = ofd.FileName;

                    // use selected file name to populate Spreadsheet Viewer
                    var myData = SpreadsheetDocument.Open(ofd.FileName, false).GetDataTableFromSpreadSheet();
                    dataGridView.DataSource = myData;

                }
            }             
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Something went wrong", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

static class Extensions
{
    // this extension is for populating the GridView with values from a spreadsheet. 
    public static DataTable GetDataTableFromSpreadSheet(this SpreadsheetDocument document, int columns = -1, bool excludeHeader = true)
    {
        var results = new DataTable();
        try
        {
            var sheets = document.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
            var id = sheets.First().Id.Value;
            var part = (WorksheetPart)document.WorkbookPart.GetPartById(id);
            var sheet = part.Worksheet;
            var data = sheet.GetFirstChild<SheetData>();
            var rows = data.Descendants<Row>();
            if (rows.Count() != 0)
            {
                var colCount = rows.First().Cast<Cell>().Count();
                if (columns > colCount || columns <= 0)
                    columns = colCount;

                foreach (var cell in rows.First().Cast<Cell>().Take(columns))
                    results.Columns.Add(cell.GetValue(document));

                foreach (var row in rows.Skip(Convert.ToInt32(excludeHeader)))
                    results.Rows.Add((from cell in row.Cast<Cell>().Take(columns) select cell.GetValue(document)).ToArray());
            }
        }
        catch (Exception)
        {
            results = new DataTable();
        }
        return results;
    }

    public static string GetValue(this Cell cell, SpreadsheetDocument document)
    {
        string result = string.Empty;
        try
        {
            if (cell != null && cell.ChildElements.Count != 0)
            {
                var part = document.WorkbookPart.SharedStringTablePart;
                if (cell.DataType != null && cell.DataType == CellValues.SharedString)
                    result = part.SharedStringTable.ChildElements[Int32.Parse(cell.CellValue.InnerText)].InnerText;
                else
                    result = cell.CellValue.InnerText;
            }
        }
        catch (Exception)
        {
            result = string.Empty;
        }
        return result;
    }
}
相关问题