012——C#打开ecxel修改数据(附教程)

(一)参考文献:[C#]将数据写入已存在的excel文件

                            C# 导入excel数据,解决关闭excel后不能释放资源的问题

(二)视频教程:https://v.qq.com/x/page/p30063aerl3.html

(三)下载地址:https://download.csdn.net/download/xiaoguoge11/11838959

 

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
        private void button1_Click(object sender, EventArgs e)
        {
                                   FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            string foldPath = "";
            if (dialog.ShowDialog() == DialogResult.OK)
               {
                    foldPath = dialog.SelectedPath + @"\" + "2019.xlsx";                             
              }
            textBox1.Text = foldPath;      

            Microsoft.Office.Interop.Excel.Application xApp = new

            Microsoft.Office.Interop.Excel.Application();

            //2.得到workbook对象,打开已有的文件
            Microsoft.Office.Interop.Excel.Workbook xBook = xApp.Workbooks.Open(foldPath);

            //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[2, 2] = 3;

            //5.保存保存WorkBook
            xBook.Save();
            //6.从内存中关闭Excel对象

            xSheet = null;
            xBook.Close();
            xBook = null;
            //关闭EXCEL的提示框
            xApp.DisplayAlerts = false;
            //Excel从内存中退出
            xApp.Quit();
            IntPtr t = new IntPtr(xApp.Hwnd);          //杀死进程的好方法,很有效
            int k = 0;
            GetWindowThreadProcessId(t, out k);
            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
            p.Kill();
            xApp = null;
        }

 

posted @ 2019-10-07 17:27  陆小果哥哥  阅读(816)  评论(0编辑  收藏  举报