C# vs2017 winForm 用Microsoft.Office.Interop.Excel導入Excel文件到datagridview(解決無法導入不規范Excel文件問題,但是導入速度很慢)


1.在項目引用NuGet中安裝Microsoft.Office.Interop.Excel

2.在cs文件頭部添加命名空間

using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using System.Diagnostics;

3.窗體界面(灰色部分是datagridview1)

4.代碼部分

using System;
using System.Windows.Forms;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using System.Diagnostics;

namespace InputExcelTest2
{
    public partial class Form_SelectFile : Form
    {
        public Form_SelectFile()
        {
            InitializeComponent();
        }
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void BtnSelectFile_Click(object sender, EventArgs e)
        {//選擇文件
            openFileDialog1.Filter = "XLS文件|*.xls|XLSX文件|*.xlsx";//篩選文件類型
            openFileDialog1.FileName = "";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                OpenExcel(openFileDialog1.FileName);
            }
            openFileDialog1.Dispose();
        }
        private void OpenExcel(string strFileName)
        {
            object missing = Missing.Value;
            Excel.Application excel = new Excel.Application();//啟動excel程序
            try
            {
                if (excel == null)
                {
                    MessageBox.Show("無法訪問Excel程序,請重新安裝Microsoft Office Excel。");
                }
                else
                {
                    excel.Visible = false;//設置調用引用的Excel文件是否可見
                    excel.UserControl = true;//設置調用引用的Excel是由用戶創建或打開的
                    // 以只讀的形式打開EXCEL文件(工作簿)想了解這堆參數請訪問https://msdn.microsoft.com/zh-cn/library/office/microsoft.office.interop.excel.workbooks.open.aspx
                    Excel.Workbook wb = excel.Application.Workbooks.Open(strFileName, missing, true, missing, missing, missing,
                     missing, missing, missing, true, missing, missing, missing, missing, missing);
                    //取得第一個工作表
                    Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];//索引從1開始 
                    //取得總記錄行數(包括標題列)  
                    int rowCount = ws.UsedRange.Cells.Rows.Count; //得到行數 
                    int colCount = ws.UsedRange.Cells.Columns.Count;//得到列數
                    //初始化datagridview1
                    dataGridView1.Rows.Clear();
                    dataGridView1.Columns.Clear();
                    //取得第一行,生成datagridview標題列(下標是從1開始的)
                    for (int i = 1; i <= colCount; i++)
                    {
                        string cellStr = ws.Cells[1, i].Value2.ToString().Trim();
                        dataGridView1.Columns.Add("column"+i,cellStr);
                    }
                    //取得數據(不包括標題列)
                    for(int i = 2; i <= rowCount; i++)
                    {//循環行
                        int index = dataGridView1.Rows.Add();
                        if (ws.Rows[i] != null)
                        {
                            for(int j = 1; j <= colCount; j++)
                            {//循環列
                                if (ws.Cells[i, j].Value2 == null)
                                {//跳過空的單元格
                                    continue;
                                }
                                dataGridView1.Rows[index].Cells[j-1].Value = ws.Cells[i, j].Value2.ToString().Trim();
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("讀取Excel文件失敗: "+ex.Message);
            }
            finally
            {
                CloseExcel(excel);//關閉Excel進程
            }
        }
        private void CloseExcel(Excel.Application excel)
        {//關閉Excel進程
            excel.Quit();
            excel = null;
            Process[] procs = Process.GetProcessesByName("excel");
            foreach (Process pro in procs)
            {
                pro.Kill();//殺掉進程  
            }
            GC.Collect();
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM