码迷,mamicode.com
首页 > Windows程序 > 详细

C# vs2017 winForm 用NOPI导入Excel文件到datagridview

时间:2018-04-22 13:08:23      阅读:1662      评论:0      收藏:0      [点我收藏+]

标签:isp   sele   cli   datagrid   row   show   filedia   cep   art   

注:这种方法有一个问题:无法读取不规范的Excel文件(一般是由于第三方工具自动生成的excel文件,如网页、xml另存为的)

1.在项目引用的NuGet安装NOPI;

 

2.在头部引用

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

3.winForm界面(灰色的部分是datagridview1):

技术分享图片

4.代码:

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)
        {//选择文件
            openFileDialog1.Filter= "XLS文件|*.xls|XLSX文件|*.xlsx";//筛选文件类型
            openFileDialog1.FileName = "";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                InputWorkbook(openFileDialog1.FileName);//执行导入
            }
            openFileDialog1.Dispose();
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
        
        //导入工作簿
        private void InputWorkbook(string filePath)
        {
            if (filePath != "")
            {
                try
                {
                    string fileType = filePath.Substring(filePath.LastIndexOf(".") + 1);//取得文件后缀
                    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);//创建文件流
                    bool isXls = true;//判断文件类型
                    if (fileType == "xlsx")
                    {
                        isXls = false;
                    }
                    IWorkbook workbook = CreateWorkbook(isXls, fs);//创建工作簿
                    ISheet sheet = workbook.GetSheetAt(0);//取得第一个工作表
                    int rowCount = sheet.LastRowNum + 1;//取得行数
                    int colCount = sheet.GetRow(0).LastCellNum;//取得列数
                    //初始化datagridview1
                    dataGridView1.Rows.Clear();
                    dataGridView1.Columns.Clear();
                    for (int c = 0; c < colCount; c++)//遍历Excel第一行,生成dataGridView1列名
                    {
                        ICell cell = sheet.GetRow(0).GetCell(c);
                        dataGridView1.Columns.Add(c.ToString() + cell.ToString(), cell.ToString());
                    }

                    for (int r = 1; r < rowCount; r++)//遍历Excel其他行,生成dataGridView1单元格内容
                    {//遍历Excel行,从第二行开始
                        IRow row = sheet.GetRow(r);
                        int index = dataGridView1.Rows.Add();
                        colCount = row.LastCellNum;
                        for (int c = 0; c < colCount; c++)
                        {//遍历每个单元格,将单元格内容填入dataGridView1单元格中
                            ICell cell = row.GetCell(c);
                            if (cell == null)//如果该单元格没有内容,跳过
                            {
                                continue;
                            }
                            dataGridView1.Rows[index].Cells[c].Value = cell.ToString();
                        }
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("导入失败: " + ex.Message);

                }
            }
            else
            {
                MessageBox.Show("请选择Excel文件");
            }
        }
        //创建工作簿
        private static IWorkbook CreateWorkbook(bool isXLS, FileStream fs)
        {
            if (isXLS)
            {
                return new HSSFWorkbook(fs);
            }
            else
            {
                return new XSSFWorkbook(fs);
            }
        }
    }
}

 

C# vs2017 winForm 用NOPI导入Excel文件到datagridview

标签:isp   sele   cli   datagrid   row   show   filedia   cep   art   

原文地址:https://www.cnblogs.com/nb08611033/p/8906047.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!