c#批量读取excel

using FastReport;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

private void Button1_Click(object sender, EventArgs e)
        {
            if (listBox1.Items.Count > 0)
            {
                List<string> lp = new List<string>();
                for (int i = 0; i <= listBox1.Items.Count - 1; i++)
                {
                    lp.Add(listBox1.Items[i].ToString());
                }
                // stopwatch.Start();
                DataTable dt = MuchExcelToDataTable(lp, true);
               dataGridView1.DataSource = dt;
               // MessageBox.Show("导入成功");
                // stopwatch.Stop();
                //label6.Text = stopwatch.ElapsedMilliseconds + "ms";
                //label4.Text = dt.Rows.Count.ToString();
            }
            else
            {
                MessageBox.Show("未选择文件夹,请选择后重试");
                return;
            }
        }

   private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.Description = "请选择Execl所在文件夹";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    listBox1.DataSource = FindFile2(dialog.SelectedPath);
                    //linkLabel1.Text = listBox1.Items.Count.ToString();
                }
                else
                    return;
            }
        }

        public List<string> FindFile2(string sSourcePath)
        {
            List<String> list = new List<string>();
            //遍历文件夹
            DirectoryInfo theFolder = new DirectoryInfo(sSourcePath);

            FileInfo[] thefileInfo = theFolder.GetFiles("*.*", SearchOption.TopDirectoryOnly);

            foreach (FileInfo NextFile in thefileInfo)  //遍历文件
            {
                list.Add(NextFile.FullName);
            }
            return list;
        }

  public static DataTable MuchExcelToDataTable(List<string> filePath, bool isColumnName)
        {
            DataTable dataTable = null;//零时存取一个Execl文件的数据
            DataTable lastdata = null;//最后返回的Datatable 
            FileStream fs = null;
            DataColumn column = null;
            DataRow dataRow = null;
            IWorkbook workbook = null;
            ISheet sheet = null;
            IRow row = null;
            ICell cell = null;
            int startRow = 0;
            bool isFisrtTime = true;
            try
            {
                if (filePath.Count > 0)
                {
                    foreach (var item in filePath)
                    {
                        using (fs = File.OpenRead(item))
                        {
                            // 2007版本
                            if (item.IndexOf(".xlsx") > 0)
                                workbook = new XSSFWorkbook(fs);
                            // 2003版本
                            else if (item.IndexOf(".xls") > 0)
                                workbook = new HSSFWorkbook(fs);
                            if (workbook != null)
                            {
                                sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet
                                //需要新建一个DataTable来将每一次读取的都合并存起来,然后这个dataTable只存每一个的
                                dataTable = new DataTable();//每次在这里重新实例化Datatable会导致数据被覆盖抹掉
                                if (sheet != null)
                                {
                                    int rowCount = sheet.LastRowNum;//总行数
                                    if (rowCount > 0)
                                    {
                                        IRow firstRow = sheet.GetRow(0);//第一行
                                        int cellCount = firstRow.LastCellNum+7;//列数 加多7列

                                        //构建datatable的列
                                        if (isColumnName)
                                        {
                                            #region
                                            /*
                                            startRow = 1;//如果第一行是列名,则从第二行开始读取
                                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                            {
                                                cell = firstRow.GetCell(i);
                                                if (cell != null)
                                                {
                                                    if (cell.StringCellValue != null)
                                                    {
                                                        column = new DataColumn(cell.StringCellValue);
                                                        dataTable.Columns.Add(column);
                                                    }
                                                }
                                            }
                                           */
                                            #endregion

                                            //自己修改的添加datatable 的列
                                            startRow =6;//我从第5列开始读
                                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                            {
                                                cell = firstRow.GetCell(i);
                                               // column = new DataColumn("column" i);
                                                dataTable.Columns.Add("column"+i);
                                            }


                                        }
                                        else
                                        {
                                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                            {
                                                column = new DataColumn("column" + (i + 1));
                                                dataTable.Columns.Add(column);
                                            }
                                        }

                                        //填充行
                                        for (int i = startRow ; i <= rowCount - 2; ++i)//
                                        {
                                            row = sheet.GetRow(i);
                                            if (row == null) continue;

                                            dataRow = dataTable.NewRow();
                                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                                            {
                                                cell = row.GetCell(j);
                                                if (cell == null)
                                                {
                                                    dataRow[j] = "";
                                                }
                                                else
                                                {
                                                    //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
                                                    switch (cell.CellType)
                                                    {
                                                        case CellType.Blank:
                                                            dataRow[j] = "";
                                                            break;
                                                        case CellType.Numeric:
                                                            short format = cell.CellStyle.DataFormat;
                                                            //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
                                                            if (format == 14 || format == 31 || format == 57 || format == 58)
                                                                dataRow[j] = cell.DateCellValue;
                                                            else
                                                                dataRow[j] = cell.NumericCellValue;
                                                            break;
                                                        case CellType.String:
                                                            dataRow[j] = cell.StringCellValue;
                                                            break;
                                                    }
                                                }

                                                if (j == 7)//如果是第7列,读取表格指定单元格的内容
                                                {
                                                    dataRow[j] = sheet.GetRow(2).GetCell(0).ToString().IndexOf(":"); //表格从0开始的,GetRow(2)就是第三行,GetCell(0)就是第一列

                                                    //MessageBox.Show(sheet.GetRow(2).GetCell(0).ToString());
                                                }
                                                if (j == 8)//如果是第8列,读取表格指定单元格的内容
                                                {
                                                    dataRow[j] = sheet.GetRow(2).GetCell(2).ToString().Substring(4);//表格从0开始的,GetRow(2)就是第三行,GetCell(2)就是第三列
                                                }
                                                if (j == 9)//如果是第9列,读取表格指定单元格的内容
                                                {
                                                    dataRow[j] = sheet.GetRow(2).GetCell(4).ToString().Substring(5);//表格从0开始的,GetRow(2)就是第三行,GetCell(2)就是第三列
                                                }
                                                if (j == 10)//如果是第10列,读取表格指定单元格的内容Substring(3)ToString().IndexOf(":")
                                                {
                                                    dataRow[j] = sheet.GetRow(3).GetCell(0).ToString().IndexOf(":");//表格从0开始的,GetRow(3)就是第四行,GetCell(0)就是第一列
                                                }
                                                if (j == 11)//如果是第11列,读取表格指定单元格的内容
                                                {
                                                    dataRow[j] = sheet.GetRow(3).GetCell(2).ToString().Substring(5);//表格从0开始的,GetRow(3)就是第四行,GetCell(2)就是第三列
                                                }
                                                if (j == 12)//如果是第12列,读取表格指定单元格的内容
                                                {
                                                    dataRow[j] = sheet.GetRow(3).GetCell(4).ToString().Substring(5);//表格从0开始的,GetRow(3)就是第四行,GetCell(4)就是第五列
                                                }
                                                if (j == 13)//如果是第13列,读取表格指定单元格的内容
                                                {
                                                    dataRow[j] = sheet.GetRow(4).GetCell(4).ToString().Substring(5);//表格从0开始的,GetRow(3)就是第四行,GetCell(4)就是第五列
                                                }

                                            }
                                            dataTable.Rows.Add(dataRow);
                                        }
                                    }
                                }

                                if (dataTable != null)
                                {
                                    //第一次的情况下,需要将整个表复制给lastdata表中,同时保存表结构
                                    if (isFisrtTime)
                                    {
                                        lastdata = dataTable.Copy();
                                        isFisrtTime = false;
                                    }
                                    //第二次则只需要将新表中的数据循环添加到表中即可
                                    else
                                    {
                                        for (int i = 0; i < dataTable.Rows.Count; i++)
                                        {
                                            lastdata.Rows.Add(dataTable.Rows[i].ItemArray);
                                            int count = lastdata.Rows.Count;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return lastdata;
            }
            catch (Exception)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                return null;
            }
        }
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄林199009

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值