Winform导入Excel Winform导出Excel 科学计数法转化、无法获取数据源,获取Excel工作簿名称

知识点:科学计数法转化

复制代码
string idcard = odr[1].ToString();
                    double d = 0;
                    try
                    {
                        idcard = Decimal.Parse(d.ToString (), System.Globalization.NumberStyles.Float).ToString();
                    }
                    catch (Exception)
                    {
                        idcard = d.ToString();
                    }
复制代码

 


获取Excel中所有工作簿名称:

复制代码
public  string[] GetExcelSheetNames(string filePath)
        { 

            Microsoft.Office.Interop.Excel.Application  excelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbooks wbs = excelApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook wb = wbs.Open(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            
            Microsoft.Office.Interop.Excel.Sheets sheets = wb.Worksheets;
             
            int count = sheets.Count;
            string[] names = new string[count];
  
            try
            {
                for (int i = 1; i <= count; i++)
                {
                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets[i];
                    names[i - 1] = sheet.Name;
                }
            }
            catch (Exception ex)
            {
                throw ex ;
            }
            
            return names;
        }
复制代码

 

获取EXCEL中的数据

方法1:用OleDbDataAdapter 笼统获取,这种是未知工作表中含有多少列

复制代码
private DataSet  GetXLSDataset(string filepath, string filename)
        {
            try
            {
                string strCon = "Provider=Microsoft.ACE.OleDb.12.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
                System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(strCon);
                Conn.Open();
                string strCom= string.Format(" select * from [{0}$]", filename);//[sheetName$]要如此格式
                System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, Conn);
                DataSet ds = new DataSet();
                myCommand.Fill(ds, "["+filename+"$]");
                return ds;
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开Excel失败,请检查是否安装或着损坏!" + ex.StackTrace, "提示");
                return null;
            }
        }
复制代码

这种方法需要注意的地方:

1:关于filepath ,这个必须是绝对路径,可通过vs工具箱中 对话框中 SaveFileDialog.FileName属性获取;

2:关于filename,这个名称是对应工作表的名称的,必须相同,此名称可通过上面提供的GetExcelSheetNames方法得到;

3:关于Excel数据查询语句 表名必须用[name$] 这种各式,从adapter中取表的时候也要用这个名字 ,此处和ADO.NET 不太一样;列和行索引都是从1开始

获取数据源方法2:

复制代码
private DataSet xsldata(string filepath, string filename)
        {
            DataSet ds = new DataSet();
            try
            {

                string strCon = "Provider=Microsoft.ACE.OleDb.12.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
                System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(strCon);
                Conn.Open();

                System.Data.OleDb.OleDbCommand cmd = Conn.CreateCommand();
                cmd.CommandText = string.Format(" select * from [{0}$]", filename);//[sheetName$]要如此格式
                System.Data.OleDb.OleDbDataReader odr = cmd.ExecuteReader();
                
                while (odr.Read())
                {
                    string name = odr[0].ToString();
                     
                }
                odr.Close();
              
                KillProcess("Excel");

            }
            catch (Exception ex)
            {
                 
            }
           
            return ds;

        }
复制代码

杀死系统中某进程方法:KillProcess(processName)

复制代码
private static void KillProcess(string processName)//杀死与Excel相关的进程
        {
            System.Diagnostics.Process myproc = new System.Diagnostics.Process();//得到所有打开的进程
            try
            {
                foreach (System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcessesByName(processName))
                {
                    if (!thisproc.CloseMainWindow())
                    {
                        thisproc.Kill();
                    }
                }
            }
            catch (Exception Exc)
            {
                throw new Exception("", Exc);
            }
        }
复制代码

 

--------------------------------------------------------------------以 上是关于导出 EXCEL-------------------------------------------------------------------------

导入EXCEL

复制代码
public static bool OutToExcelFromDataGridView(string fileName, DataSet ds)
        {
            
            int columnIndex = 1;//列索引
            /*建立Excel对象*/
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            if (excel == null)
            {
                MessageBox.Show("无法创建Excel对象,可能您的计算机未安装Excel!");
                return false;
            }
            try
            {
                excel.Application.Workbooks.Add(true);
                excel.Visible = false;
                
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet;
                 
                //生成字段名称
                List<string> columns = new List<string>();
                columns.Add("单位名称"); 
                columns.Add("姓名");
                columns.Add("手机号");
                columns.Add("身份证号");
               
                int columnCount = columns.Count;
                for (int i = 0; i < columnCount; i++)
                {
                    excel.Cells[1, columnIndex] = columns[i];
                    (excel.Cells[1, columnIndex] as Range).HorizontalAlignment = XlHAlign.xlHAlignLeft;//字段居中
                    columnIndex++;
                }

                //填充数据              
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                     
                    for (int j = 0; j < ds.Table[0].Columns.Count; j++)
                    { 
                        string value=ds.Table[0].Row[i][j].ToString();
                        excel.Cells[i + 1, j + 1] = "'" + value;
                    }

                }
                worksheet.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            }
            catch  {
                
            }
            finally
            {
                excel.Quit();
                excel = null;
                GC.Collect();
            }
            KillProcess("Excel");
            return true;

        }
复制代码

你可能感兴趣的:(WinForm)