导入excle数据

导入excle数据

1.if (File.Exists(strFileName)) // 当文件存在时
            {
                m_fileName = strFileName;
            }
            else
            {
                throw new Exception(string.Format("文件:[{0}] 不存在!", m_fileName));
            }
            this.gridView.DataSource = ExcelToDataTable(m_fileName, "Sheet1");

2.

 /// <summary>
        /// 将Excel导入DataTable中(Excel第一行为DataTable列名)
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        private System.Data.DataTable ExcelToDataTable(string filePath, string sheetName)
        {
            ApplicationClass app = new ApplicationClass();
            app.Visible = false;

            //打开Excel
            WorkbookClass w = (WorkbookClass)app.Workbooks.Open(filePath, Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value);

            object missing = Type.Missing;
            Sheets sheets = w.Worksheets;
            m_dataTable = new System.Data.DataTable();

            foreach (Worksheet sheet in sheets)
            {
                if (sheet.Name != sheetName)
                {
                    //构建DataTable结构
                    for (int j = 1; j <= sheet.Cells.CurrentRegion.Columns.Count; j++)
                    {
                        //Excel第一行数据为DataTable列名
                        Microsoft.Office.Interop.Excel.Range tem = (Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, j];
                        m_dataTable.Columns.Add(tem.Text.ToString());
                    }
                    //Excel数据加载到DataTable
                    for (int i = 2; i <= sheet.Cells.CurrentRegion.Rows.Count; i++)
                    {
                        DataRow row = m_dataTable.NewRow();
                        for (int j = 1; j <= sheet.Cells.CurrentRegion.Columns.Count; j++)
                        {
                            Microsoft.Office.Interop.Excel.Range tem = (Microsoft.Office.Interop.Excel.Range)sheet.Cells[i, j];
                            row[j - 1] = tem.Text.ToString();
                        }
                        m_dataTable.Rows.Add(row);
                    }
                    break;
                }
            }
            app.Quit();
            app = null;

            return m_dataTable;
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值