用开源方式NPOI 读取远程共享文件夹中的Excel数据到DataSet

先要引用NPOI,NuGet上面有
用开源方式NPOI 读取远程共享文件夹中的Excel数据到DataSet_第1张图片

1.建立连接

      /// 
        /// 连接远程共享文件夹
        /// 
        /// 远程共享文件夹的路径
        /// 用户名
        /// 密码
        /// 
        public bool connectState(string path, string userName, string passWord)
        {
            bool Flag = false;
            Process proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                /*
                * 1)删除已有的连接,避免出现“一个用户使用...多重连接”的问题。
                * 如果提示“列表是空的”,表示当前没有任何关联连接;
                * 如果提示“您有如下远程连接... 继续运行会取消连接”,输入“Y”或者“y”
                */
                proc.StandardInput.WriteLine("net use * /del /y");
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (string.IsNullOrEmpty(errormsg))
                {
                    Flag = true;
                }
                else
                {
                    throw new Exception(errormsg);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }

2.读取数据到DataSet

        /// 
        /// 
        /// 
        /// 连接账号
        /// 密码
        /// 开始行
        /// 开始列
        /// Sheet
        /// 
       public DataSet LoadShareFileToDataSet(string account, string pwd, int startrowindex, int startcolumnindex, string sheetName)
        {
            bool status = false;
            DataSet ds = new DataSet();
            IWorkbook workbook = null;
            try
            {
                //连接共享文件夹,可以配置再配置文件里面
                status = connectState(@"\\192.168.1.100\Import", account, pwd);
                if (status)
                {
                    //共享文件夹的目录
                    DirectoryInfo theFolder = new DirectoryInfo(@"\\192.168.1.100\Import");
                    if (theFolder.Exists && theFolder.GetFiles().Count() != 0)
                    {
                        foreach (var itemFile in theFolder.GetFiles())
                        {
                            FileStream fileStream = new FileStream(itemFile.FullName, FileMode.Open,FileAccess.Read, FileShare.ReadWrite);
                            DataTable dt = new DataTable();
                            if (fileStream != null && fileStream.Length != 0)
                            {
                                if (itemFile.Name.IndexOf(".xlsx") > 0)//2007之后版本
                                    workbook = new XSSFWorkbook(fileStream);
                                else if (itemFile.Name.IndexOf(".xls") > 0)//2007之前版本
                                    workbook = new HSSFWorkbook(fileStream);
                                ISheet sheet = null;
                                if (!string.IsNullOrEmpty(sheetName))
                                {
                                    sheet = workbook.GetSheet(sheetName);
                                }
                                else
                                {
                                    sheet = workbook.GetSheetAt(0);
                                }
                                int rowCount = sheet.LastRowNum;
                                int rowStart = sheet.FirstRowNum;
                                //这里就看具体需求了
                                var rows0 = sheet.GetRow(0);
                                //创建DataTable的Column
                                foreach (var co in rows0.Cells)
                                {
                                    var b = co.StringCellValue;
                                    var c = co.ToString();
                                    dt.Columns.Add(b, Type.GetType("System.String"));
                                }
                                int columnCount = rows0.LastCellNum;
                                DataRow dr = null;
                                for (int i = startrowindex; i < rowCount; i++)
                                {
                                    var row = sheet.GetRow(i + 1);
                                    if (row == null || row.FirstCellNum < 0) continue;
                                    dr = dt.NewRow();
                                    for (int j = startcolumnindex; j < row.Cells.Count; j++)
                                    {
                                       //用GetCell获取单元格没有为null,不会抛异常
                                        var cell = row.GetCell(j);
                                        if (cell != null)
                                        {
                                            //特殊类型
                                            if (cell.CellType == CellType.Numeric)
                                            {
                                                if (DateUtil.IsCellDateFormatted(cell))
                                                {
                                                    dr[j] = row.GetCell(j).DateCellValue;
                                                }
                                                else
                                                {
                                                    dr[j] = row.GetCell(j).ToString().Trim();
                                                }
                                            }
                                            else
                                            {
                                                dr[j] = row.GetCell(j).ToString().Trim();
                                            }
                                        }

                                    }
                                    dt.Rows.Add(dr);
                                }
                            }
                            ds.Tables.Add(dt);
                        }
                    }
                }
                return ds;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

你可能感兴趣的:(应用)