zoukankan      html  css  js  c++  java
  • c# 读取和写入excel数据

    1. 读取

    private void button1_Click(object sender, EventArgs e)
            {
                DataTable dt = GetDataFromExcelByConn();
                dataGridView1.DataSource = dt.DefaultView;
            }
    
            DataTable GetDataFromExcelByConn(bool hasTitle = false)
            {
                OpenFileDialog openFile = new OpenFileDialog();
                openFile.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
                openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                openFile.Multiselect = false;
                if (openFile.ShowDialog() == DialogResult.Cancel) return null;
                var filePath = openFile.FileName;
                string fileType = System.IO.Path.GetExtension(filePath);
                if (string.IsNullOrEmpty(fileType)) return null;
    
                using (DataSet ds = new DataSet())
                {
                    // Microsoft.Jet.OLEDB.{0}.0.12.0
                    string strCon = string.Format("Provider=Microsoft.ACE.OLEDB.{0}.0;" +
                                    "Extended Properties="Excel {1}.0;HDR={2};IMEX=1;";" +
                                    "data source={3};",
                                    (fileType == ".xls" ? 4 : 12), (fileType == ".xls" ? 8 : 12), (hasTitle ? "Yes" : "NO"), filePath);
                    string strCom = " SELECT * FROM [Sheet1$]";
                    using (OleDbConnection myConn = new OleDbConnection(strCon))
                    using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn))
                    {
                        myConn.Open();
                        myCommand.Fill(ds);
                    }
                    if (ds == null || ds.Tables.Count <= 0) return null;
                    return ds.Tables[0];
                }
            }
    

      

    未在本地计算机上注册“Microsoft.Jet.OLEDB.12.0”提供程序
    遇到此类问题有以下几种解决方案:

    解决方案一:下载安装AccessDatabaseEngine.exe,然后重启电脑。

    解决方案二:用Microsoft.ACE.OLEDB.12.0,替代Microsoft.Jet.OLEDB.12.0 。

    解决方案三:更改应用程序池的设置

    2.写入

    项目添加应用 Microsoft.Office.Interop.Excel.dll 文件

           //将数据写入已存在Excel
            public static void writeExcel(string result, string filepath)
            {
                //1.创建Applicaton对象
                Microsoft.Office.Interop.Excel.Application xApp = new
    
                Microsoft.Office.Interop.Excel.Application();
    
                //2.得到workbook对象,打开已有的文件
                Microsoft.Office.Interop.Excel.Workbook xBook = xApp.Workbooks.Open(filepath,
                                      Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                                      Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                                      Missing.Value, Missing.Value, Missing.Value, Missing.Value);
    
                //3.指定要操作的Sheet
                Microsoft.Office.Interop.Excel.Worksheet xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[1];
    
                //在第一列的左边插入一列  1:第一列
                //xlShiftToRight:向右移动单元格   xlShiftDown:向下移动单元格
                //Range Columns = (Range)xSheet.Columns[1, System.Type.Missing];
                //Columns.Insert(XlInsertShiftDirection.xlShiftToRight, Type.Missing);
    
                //4.向相应对位置写入相应的数据
                xSheet.Cells[1][2] = result;
    
                //5.保存保存WorkBook
                xBook.Save();
                //6.从内存中关闭Excel对象
    
                xSheet = null;
                xBook.Close();
                xBook = null;
                //关闭EXCEL的提示框
                xApp.DisplayAlerts = false;
                //Excel从内存中退出
                xApp.Quit();
                xApp = null;
            }
    

      

    3.关闭Excel进程

            /// <summary>
            /// 关闭Excel进程
            /// </summary>
            /// <param name="excelPath"></param>
            /// <param name="excel"></param>
            /// <param name="wb"></param>
            public void ClosePro(string excelPath, Excel.Application excel, Excel.Workbook wb)
            {
                Process[] localByNameApp = Process.GetProcessesByName(excelPath);//获取程序名的所有进程
                if (localByNameApp.Length > 0)
                {
                    foreach (var app in localByNameApp)
                    {
                        if (!app.HasExited)
                        {
                            #region
                            ////设置禁止弹出保存和覆盖的询问提示框   
                            //excel.DisplayAlerts = false;
                            //excel.AlertBeforeOverwriting = false;
    
                            ////保存工作簿   
                            //excel.Application.Workbooks.Add(true).Save();
                            ////保存excel文件   
                            //excel.Save("D:" + "\test.xls");
                            ////确保Excel进程关闭   
                            //excel.Quit();
                            //excel = null; 
                            #endregion
                            app.Kill();//关闭进程  
                        }
                    }
                }
                if (wb != null)
                    wb.Close(true, Type.Missing, Type.Missing);
                excel.Quit();
                // 安全回收进程
                System.GC.GetGeneration(excel);
            }
    

      

  • 相关阅读:
    1015. 德才论
    1014. 福尔摩斯的约会
    1013. 数素数
    1012. 数字分类
    1011. A+B和C
    1010. 一元多项式求导
    1009. 说反话
    1008. 数组元素循环右移问题
    1007. 素数对猜想
    1006. 换个格式输出整数
  • 原文地址:https://www.cnblogs.com/wzihan/p/14860464.html
Copyright © 2011-2022 走看看