C# vs2017 winForm uses Microsoft.Office.Interop.Excel to import Excel files into datagridview (solves the problem of not being able to import irregular Excel files, but the import speed is very slow)

1. Install Microsoft.Office.Interop.Excel in the project reference NuGet

2. Add a namespace to the head of the cs file

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

3. Form interface (the gray part is datagridview1)

4. Code section

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)
        { // Select file 
            openFileDialog1.Filter = " XLS file|*.xls|XLSX file|*.xlsx " ; // Filter file type 
            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(); // Start the excel program 
            try
            {
                if (excel == null)
                {
                    MessageBox.Show( " Cannot access the Excel program, please reinstall Microsoft Office Excel. " );
                }
                else
                {
                    excel.Visible = false ; // Set whether the Excel file referenced by the call is visible 
                    excel.UserControl = true ; // Set the Excel referenced by the call is created or opened by the user
                     // Open the EXCEL file (workbook) as read-only To learn about this bunch of parameters, please visit https://msdn.microsoft.com/en-us/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);
                     // Get the first worksheet 
                    Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[ 1 ]; // Index starts at 1 
                     // Get the total number of rows (including the title column)   
                    int rowCount = ws.UsedRange.Cells.Rows.Count; // Get the number of rows 
                    int colCount = ws.UsedRange.Cells.Columns.Count; // Get the number of columns
                     // Initialize datagridview1 
                    dataGridView1.Rows.Clear();
                    dataGridView1.Columns.Clear();
                    // Get the first row and generate the datagridview title column (the subscript starts from 1) 
                    for ( int i = 1 ; i <= colCount; i++ )
                    {
                        string cellStr = ws.Cells[1, i].Value2.ToString().Trim();
                        dataGridView1.Columns.Add("column"+i,cellStr);
                    }
                    // Get data (excluding header column) 
                    for ( int i = 2 ; i <= rowCount; i++ )
                    {//循环行
                        int index = dataGridView1.Rows.Add();
                        if (ws.Rows[i] != null)
                        {
                            for(int j = 1; j <= colCount; j++)
                            { // loop column 
                                if (ws.Cells[i, j].Value2 == null )
                                { // Skip empty cells 
                                    continue ;
                                }
                                dataGridView1.Rows[index].Cells[j-1].Value = ws.Cells[i, j].Value2.ToString().Trim();
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show( " Failed to read Excel file: " + ex.Message);
            }
            finally
            {
                CloseExcel(excel); // Close the Excel process 
            }
        }
        private void CloseExcel(Excel.Application excel)
        { // Close the Excel process 
            excel.Quit();
            excel = null;
            Process[] procs = Process.GetProcessesByName("excel");
            foreach (Process pro in procs)
            {
                pro.Kill(); // kill the process   
            }
            GC.Collect();
        }
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324727469&siteId=291194637