Excel data read into the DataSet

Original link: http://www.cnblogs.com/tianjinquan/p/3972346.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.IO;
using System.Xml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;

namespace ECLink.Common
{
    /// <summary>
    /// 采用openxml方式把excel转换成DataSet
    /// </summary>
    public class ExcelHelper
    {
        public ExcelHelper()
        {

        }
        /// <Summary> 
        /// an Excel table into multiple single data set object DataSet
         ///  </ Summary> 
        ///  <param name = "filePath"> Excel file path </ param> 
        ///  <Returns> transformed datasets </ Returns> 
        public   the dataSet ExcelToDataSet ( String filePath) 
        { 
            the dataSet dataSet A = new new the dataSet ();
             the try 
            { 
                the using (SpreadsheetDocument spreadDocument = SpreadsheetDocument.Open (filePath, to false )) 
                { 
                    // the specified objects workbookPart 
                    workbookPart workBookPart = spreadDocument.WorkbookPart;
                    //获取Excel中SheetName集合
                    List<string> sheetNames = GetSheetNames(workBookPart);

                    foreach (string sheetName in sheetNames)
                    {
                        DataTable dataTable = WorkSheetToTable(workBookPart, sheetName);
                        if (dataTable != null)
                        {
                            dataSet.Tables.Add(dataTable);//将表添加到数据集
                        }
                    }
                } 
            }
            the catch (Exception exp) 
            { 
                the throw  new new Exception ( " might Excel is open, turn off operation again! " ); 
            } 
            return dataSet A; 
        } 

        ///  <Summary> 
        // Create DataTable objects and in accordance with the table name WorkbookPart
         ///  </ Summary> 
        ///  <param name = "workBookPart"> workbookPart Object </ param> 
        ///  <param name = "tableName"> table </ param> 
        ///  <Returns> transformed the DataTable </ returns A> 
        public DataTable WorkSheetToTable (workbookPart workBookPart,string sheetName)
        {
            //创建Table
            DataTable dataTable = new DataTable(sheetName);

            //根据WorkbookPart和sheetName获取该Sheet下所有行数据
            IEnumerable<Row> sheetRows = GetWorkBookPartRows(workBookPart, sheetName);
            IEnumerable<Column> sheetColumns = GetWorkBookPartColumns(workBookPart, sheetName);

            if (sheetRows == null || sheetRows.Count() <= 0)
            {
                return null;
            }

            SharedStringTable stringTable =workBookPart.SharedStringTablePart.SharedStringTable;
             // import data into the DataTable, assumed that the first column name acts, after the second row of data 
            the foreach (Row Row in sheetRows) 
            { 
                // Get the column header in Excel 
                IF (row.RowIndex == . 1 ) 
                { 
                    GetDataColumn (Row, stringTable, REF the dataTable); 
                } 
                the else 
                { 
                    GetDataRow (Row, stringTable, REF the dataTable); 
                } 
            } 
            return the dataTable; 
        } 
 
        ///  <Summary>
         /// WorkbookPart accessories SheetName according
         ///  </ Summary>
        /// <param name="workBookPart"></param>
        /// <returns>SheetName集合</returns>
        private List<string> GetSheetNames(WorkbookPart workBookPart)
        {
            List<string> sheetNames = new List<string>();
            Sheets sheets = workBookPart.Workbook.Sheets;
            foreach (Sheet sheet in sheets)
            {
                string sheetName =sheet.Name;
                 IF (! String .IsNullOrEmpty (sheetName)) 
                { 
                    sheetNames.Add (sheetName); 
                } 
            } 
            return sheetNames; 
        } 

        ///  <Summary> 
        /// Get all the data in Row Sheet according WorkbookPart and sheetName
         // /  </ Summary> 
        ///  <param name = "workBookPart"> WorkbookPart Object </ param> 
        ///  <param name = "sheetName"> SheetName </ param> 
        ///  <Returns> All Row at the SheetName data </ Returns> 
        public the IEnumerable < Row> GetWorkBookPartRows (workbookPart workBookPart,string sheetName)
        {
            IEnumerable<Row> sheetRows = null;
            //根据表名在WorkbookPart中获取Sheet集合
            IEnumerable<Sheet> sheets = workBookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName);
            if (sheets.Count() == 0)
            {
                return null;//没有数据
            }

            WorksheetPart workSheetPart = workBookPart.GetPartById(sheets.First().Id) as WorksheetPart;
            //Gets the line obtained in Excel 
            sheetRows = workSheetPart.Worksheet.Descendants <Row> ();
             return sheetRows; 
        } 

        ///  <Summary> 
        /// WorkbookPart sheetName and get all the data in Row Sheet according
         ///  </ Summary> 
        ///  <param name = "workBookPart"> WorkbookPart Object </ param> 
        ///  <param name = "sheetName"> SheetName </ param> 
        ///  <Returns> All the data in Row SheetName </ Returns> 
        public the IEnumerable <the Column> GetWorkBookPartColumns (WorkbookPart workBookPart,string sheetName)
        {
            IEnumerable <the Column> sheetColumns = null ;
            // get the collection in WorkbookPart Sheet in accordance with the table name
            IEnumerable<Sheet> sheets = workBookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName);
            if (sheets.Count() == 0)
            {
                return null;//没有数据
            }

            WorksheetPart workSheetPart = workBookPart.GetPartById(sheets.First().Id) as WorksheetPart;
            
            sheetColumns = workSheetPart.Worksheet.Descendants<Column>(); //获取Excel中得到的行

            return sheetColumns;
        }


        /// <summary>
        /// 获取Excel中多表的表名
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private List<string> GetExcelSheetNames(string filePath)
        {
            string sheetName = string.Empty;
            List<string> sheetNames = new List<string>();//所有Sheet表名
            using (SpreadsheetDocument spreadDocument = SpreadsheetDocument.Open(filePath, false))
            {
                WorkbookPart workBook = spreadDocument.WorkbookPart;
                Stream stream = workBook.GetStream(FileMode.Open);
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(stream);

                XmlNamespaceManager xmlNSManager = new XmlNamespaceManager(xmlDocument.NameTable);
                xmlNSManager.AddNamespace("default", xmlDocument.DocumentElement.NamespaceURI);
                XmlNodeList nodeList = xmlDocument.SelectNodes("//default:sheets/default:sheet", xmlNSManager);

                the foreach (the XmlNode Node in the nodeList) 
                { 
                    sheetName = node.Attributes [ " name " ] .Value; 
                    sheetNames.Add (sheetName); 
                } 
            } 
            return sheetNames; 
        } 

        #region using excel openxml manner to convert the dataTable /// <Summary> /// Construction DataTable column
         /// </ Summary> /// <param name = "row"> the OpenXML row object defined </ param> /// <param name = "stringTablePart"> </ param> / // <param name="dt">

         
         
         
         
         DataTable objects need to return </ param> 
        /// <returns></returns>
        public void GetDataColumn(Row row, SharedStringTable stringTable, ref DataTable dt)
        {
            DataColumn col = new DataColumn();
            Dictionary<string, int> columnCount = new Dictionary<string, int>();
            foreach (Cell cell in row)
            {
                string cellVal = GetValue(cell, stringTable);
                col = new DataColumn(cellVal);
                if (IsContainsColumn(dt, col.ColumnName))
                {
                    if (!columnCount.ContainsKey(col.ColumnName))
                        columnCount.Add(col.ColumnName, 0);
                    col.ColumnName = col.ColumnName + (columnCount[col.ColumnName]++);
                }
                dt.Columns.Add(col);
            }
        }
        /// <summary>
        /// 构建DataTable的每一行数据,并返回该Datatable
        /// </summary>
        /// <param name="row">OpenXML的行</param>
        /// <param name = "stringTablePart"> </ param> 
        ///  <param name = "dt"> the DataTable </ param> 
        Private  void GetDataRow (Row Row, SharedStringTable stringTable, REF the DataTable dt) 
        { 
            // reading algorithm: Press row eleven read cell unit, if the entire row is a null data 
            the DataRow DR = dt.NewRow ();
             int I = 0 ;
             int nullRowCount = I;
             the foreach (the cell cell in row) 
            { 
                String cellVal = the GetValue (cell, stringTable );
                 IF (cellVal == String.Empty)
                {
                    nullRowCount++;
                }
                dr[i] = cellVal;
                i++;
            }
            if (nullRowCount != i)
            {
                dt.Rows.Add(dr);
            }
        }
        /// <summary>
        /// 获取单位格的值
        /// </summary>
        /// <param name="cell"></param>
        /// <param name="stringTablePart"></param>
        /// <returns></returns>
        private stringThe GetValue (the Cell Cell, SharedStringTable stringTable) 
        { 
            // Because SharedStringTable, the need to obtain the data in Excel SharedStringTable index data storage 
            String value = String .Empty;
             the try 
            { 
                IF (cell.ChildElements.Count == 0 )
                     return value ; 
                value = Double .Parse (cell.CellValue.InnerText) .ToString ();
                 IF (! (cell.DataType = null ) && (cell.DataType == CellValues.SharedString)) 
                { 
                    value = stringTable.ChildElements[Int32.Parse(value)].InnerText;
                }
            }
            catch (Exception)
            {
                value = "N/A";
            }
            return value;
        }
        /// <summary>
        /// 判断网格是否存在列
        /// </summary>
        /// <param name="dt">网格</param>
        /// <param name="columnName">列名</param>
        /// <returns></returns>
        public bool IsContainsColumn(DataTable dt, string columnName)
        {
            if (dt == null || columnName == null)
            {
                return false;
            }
            return dt.Columns.Contains(columnName);
        }

        #endregion 

        #region SaveCell
        private void InsertTextCellValue(Worksheet worksheet, string column, uint row, string value)
        {
            Cell cell = ReturnCell(worksheet, column, row);
            CellValue v = new CellValue();
            v.Text = value;
            cell.AppendChild(v);
            cell.DataType = new EnumValue<CellValues>(CellValues.String);
            worksheet.Save();
        }
        private void InsertNumberCellValue(Worksheet worksheet, string column, uint row, string value)
        {
            Cell cell = ReturnCell(worksheet, column, row);
            CellValue v = new CellValue();
            v.Text = value;
            cell.AppendChild(v);
            cell.DataType = new EnumValue<CellValues>(CellValues.Number);
            worksheet.Save();
        }
        private static Cell ReturnCell(Worksheet worksheet, string columnName, uint row)
        {
            Row targetRow = ReturnRow(worksheet, row);

            if (targetRow == null)
                return null;

            return targetRow.Elements<Cell>().Where(c =>
               string.Compare(c.CellReference.Value, columnName + row,
               true) == 0).First();
        }
        private static Row ReturnRow(Worksheet worksheet, uint row)
        {
            return worksheet.GetFirstChild<SheetData>().
            Elements<Row>().Where(r => r.RowIndex == row).First();
        }
        #endregion
    }
}

 

Reproduced in: https: //www.cnblogs.com/tianjinquan/p/3972346.html

Guess you like

Origin blog.csdn.net/weixin_30617561/article/details/95144854