C# vs2017 winForm uses NOPI to import Excel files to datagridview

1. Install NOPI in NuGet referenced by the project;

 

2. Quote in the header

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;

3.winForm interface (the gray part is datagridview1):

4. Code:

using System;
using System.Windows.Forms;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;

namespace InputExcelTest
{
    public partial class Form_SelectFile : Form
    {
        public Form_SelectFile()
        {
            InitializeComponent();
        }

        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)
            {
                InputWorkbook(openFileDialog1.FileName); //Execute import
            }
            openFileDialog1.Dispose();
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
        
        //导入工作簿
        private void InputWorkbook(string filePath)
        {
            //string filePath = TxbFilePath.Text.Trim();
            if (filePath != "")
            {
                try
                {
                    string fileType = filePath.Substring(filePath.LastIndexOf( " . " ) + 1 ); // Get the file suffix 
                    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); // Create a file stream 
                    bool isXls = true ; // Determine the file type 
                    if (fileType == " xlsx " )
                    {
                        isXls = false;
                    }
                    IWorkbook workbook = CreateWorkbook(isXls, fs); // Create a workbook 
                    ISheet sheet = workbook.GetSheetAt( 0 ); // Get the first worksheet 
                    int rowCount = sheet.LastRowNum + 1 ; // Get the number of rows 
                    int colCount = sheet.GetRow( 0 ).LastCellNum; // Get the number of columns
                     // Initialize datagridview1 
                    dataGridView1.Rows.Clear();
                    dataGridView1.Columns.Clear();
                    for ( int c = 0 ; c < colCount; c++) // Traverse Excel columns and generate dataGridView1 column names 
                    {
                        ICell cell = sheet.GetRow(0).GetCell(c);
                        dataGridView1.Columns.Add(c.ToString() + cell.ToString(), cell.ToString());
                    }

                    for ( int r = 1 ; r < rowCount; r++) // Traverse Excel to generate dataGridView1 cell content 
                    { // Traverse Excel rows, starting from the second row 
                        IRow row = sheet.GetRow(r);
                         int index = dataGridView1. Rows.Add();
                        colCount = row.LastCellNum;
                        for (int c = 0; c < colCount; c++)
                        { // Traverse the Excel column and fill the cell content into the dataGridView1 cell 
                            ICell cell = row.GetCell(c);
                             if (cell == null ) // If the cell has no content, skip 
                            {
                                 continue ;
                            }
                            dataGridView1.Rows[index].Cells[c].Value = cell.ToString();
                        }
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show( " Import failed: " + ex.Message);

                }
            }
            else
            {
                MessageBox.Show( " Please select an Excel file " );
            }
        }
        // Create workbook 
        private  static IWorkbook CreateWorkbook( bool isXLS, FileStream fs)
        {
            if (isXLS)
            {
                return new HSSFWorkbook(fs);
            }
            else
            {
                return new XSSFWorkbook(fs);
            }
        }
    }
}

 

Guess you like

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