1. 程式人生 > >【C#】Excel動態匯入多張表

【C#】Excel動態匯入多張表

前言

    昨天去一家公司面試,專案經理提了一個專案很緊的專案需求,Excel動態匯入多張表,同時根據給出公式做表內及表間的資料校驗,晚上回來之後一直到今天下午就一直再搗鼓著,不過遺憾的是沒能完美實現上述功能。不過卻實現了簡單實現了Excel的多表匯入。下面是我的程式碼思路。

實現

1、新增NOPI元件引用



2、新增ExcelHelper類

using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace Vevisoft.Excel.Core
{
    /// <summary>
    /// 使用NOPI讀取Excel資料
    /// </summary>
    public class ExcelImportCore
    {
        private IWorkbook _workbook;
        private string _filePath;

        public List<string> SheetNames { get; set; }

        public ExcelImportCore()
        {
            SheetNames = new List<string>();
            //LoadFile(_filePath);
        }

        #region Excel資訊

        /// <summary>
        /// 獲取Excel資訊
        /// </summary>
        /// <param name="filePath"></param>
        public List<string> LoadFile(string filePath)
        {
            var prevCulture = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            var stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            _filePath = filePath;
            SheetNames = new List<string>();
            using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                _workbook = WorkbookFactory.Create(fs);
            }

            stopwatch.Stop();
            Console.WriteLine("ReadFile:" + stopwatch.ElapsedMilliseconds / 1000 + "s");

            return GetSheetNames();
        }

        /// <summary>
        /// 獲取SHeet名稱
        /// </summary>
        /// <returns></returns>
        private List<string> GetSheetNames()
        {
            var count = _workbook.NumberOfSheets;
            for (int i = 0; i < count; i++)
            {
                SheetNames.Add(_workbook.GetSheetName(i));
            }
            return SheetNames;
        }

        #endregion


        #region 獲取資料來源

        /// <summary>
        /// 獲取所有資料,所有sheet的資料轉化為datatable。
        /// </summary>
        /// <param name="isFirstRowCoumn">是否將第一行作為列標題</param>
        /// <returns></returns>
        public DataSet GetAllTables(bool isFirstRowCoumn)
        {
            var stopTime = new System.Diagnostics.Stopwatch();
            stopTime.Start();
            var ds = new DataSet();

            foreach (var sheetName in SheetNames)
            {
                ds.Tables.Add(ExcelToDataTable(sheetName, isFirstRowCoumn));
            }
            stopTime.Stop();
            Console.WriteLine("GetData:" + stopTime.ElapsedMilliseconds / 1000 + "S");
            return ds;
        }

        /// <summary>
        /// 獲取第<paramref name="idx"/>的sheet的資料
        /// </summary>
        /// <param name="idx">Excel檔案的第幾個sheet表</param>
        /// <param name="isFirstRowCoumn">是否將第一行作為列標題</param>
        /// <returns></returns>
        public DataTable GetTable(int idx, bool isFirstRowCoumn)
        {
            if (idx >= SheetNames.Count || idx < 0)
                throw new Exception("Do not Get This Sheet");
            return ExcelToDataTable(SheetNames[idx], isFirstRowCoumn);
        }

        /// <summary>
        /// 獲取sheet名稱為<paramref name="sheetName"/>的資料
        /// </summary>
        /// <param name="sheetName">Sheet名稱</param>
        /// <param name="isFirstRowColumn">是否將第一行作為列標題</param>
        /// <returns></returns>
        public DataTable GetTable(string sheetName, bool isFirstRowColumn)
        {
            return ExcelToDataTable(sheetName, isFirstRowColumn);
        }

        #endregion

        #region 方法

        /// <summary>
        /// 將excel中的資料匯入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名稱</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
        {
            ISheet sheet = null;
            var data = new DataTable();
            data.TableName = sheetName;
            int startRow = 0;
            try
            {
                sheet = sheetName != null ? _workbook.GetSheet(sheetName) : _workbook.GetSheetAt(0);
                if (sheet != null)
                {
                    var firstRow = sheet.GetRow(0);
                    if (firstRow == null)
                        return data;
                    int cellCount = firstRow.LastCellNum; //一行最後一個cell的編號 即總的列數
                    startRow = isFirstRowColumn ? sheet.FirstRowNum + 1 : sheet.FirstRowNum;

                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                    {
                        //.StringCellValue;
                        var column = new DataColumn(Convert.ToChar(((int)'A') + i).ToString());
                        if (isFirstRowColumn)
                        {
                            var columnName = firstRow.GetCell(i).StringCellValue;
                            column = new DataColumn(columnName);
                        }
                        data.Columns.Add(column);
                    }


                    //最後一列的標號
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //沒有資料的行預設是null       

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理,沒有資料的單元格都預設是null
                                dataRow[j] = row.GetCell(j, MissingCellPolicy.RETURN_NULL_AND_BLANK).ToString();
                        }
                        data.Rows.Add(dataRow);
                    }
                }
                else throw new Exception("Don not have This Sheet");

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }

        #endregion
    }
}

3、在winForm窗體中新增Tabcontrol空間作為資料顯示的容器

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;

using Vevisoft.Excel.Core;

namespace ExcelProject
{
    public partial class FrmShow : Form
    {
        public FrmShow()
        {
            InitializeComponent();
        }

        private void FrmShow_Load(object sender, EventArgs e)
        {}


        private void button1_Click(object sender, EventArgs e)
        {
            var importCore = new ExcelImportCore();
            var opdiag = new OpenFileDialog();
            tabControl1.TabPages.Clear();
            if (opdiag.ShowDialog() == DialogResult.OK)
            {
                importCore.LoadFile(opdiag.FileName);
                var ds = importCore.GetAllTables(false);
                //  
                for (int i = 0; i < importCore.SheetNames.Count; i++)
                {
                    var tp = new TabPage { Text = Name = importCore.SheetNames[i] };
                    tabControl1.TabPages.Add(tp);
                    //新增資料來源  
                    var dgv = new DataGridView
                    {
                        //AutoGenerateColumns = false,  
                        DataSource = ds.Tables[i],
                        Dock = DockStyle.Fill
                    };
                    tp.Controls.Add(dgv);

                }
            }  
        }

       
    }
}

缺點:只能匯入表格中首行首列不為空的表,正在努力嘗試匯入的時候保證樣式相同。

總結

    面試總結:真心虐心,水平有待提高。不過資料校驗這一部分經過查詢資料,有個不太肯定的思路:利用XML配置校驗規則,然後讀取顯示在系統中的資料進行校驗。遺憾的經歷,確立目標努力提高自己。