如何将Excel覆盖到C#?我有一个C#表单,我要在Excel文件中添加数据然后覆盖它这是我的代码 [英] How Can I Overwrite Excel To C#? I Have A C# Form And I'm Going To Add A Data In A Excel File Then Overwrite It This Is My Code

查看:153
本文介绍了如何将Excel覆盖到C#?我有一个C#表单,我要在Excel文件中添加数据然后覆盖它这是我的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void exportToExcelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            for (int row = 0; row <= dataGridView1.RowCount - 1; row++)
            {
                for (int column = 0; column <= dataGridView1.RowCount - 1; column++)
                {
                    DataGridViewCell cell = dataGridView1[column, row];
                    xlWorkSheet.Cells[row + 2, column + 2] = cell.Value;
                }
            }
            xlWorkBook.SaveAs("sample.xls",Excel.XlFileFormat.xlWorkbookNormal,misValue,misValue,misValue,misValue,Excel.XlSaveAsAccessMode.xlExclusive,misValue,misValue,misValue,misValue,misValue);
            xlWorkBook.Close(true,misValue,misValue);

            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

        }

        public void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while realeasing object" + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

推荐答案

覆盖?为什么在添加数据后覆盖Excel?

如果你想覆盖原始数据。只需清除它并写入新数据。

否则,您可以将原始数据恢复为SQL。然后覆盖excel。

使用ASP中的C#将数据从excel导入SQL服务器。 NET

不是很明白你想要实现什么,关于excel操作你可以尝试一些免费的 API for .NET
Overwrite? Why overwrite the Excel after adding data?
If you want to cover the original data.Just clear it and write new data.
Else you can restore the original data to SQL. And then overwrite the excel.
Import Data from excel to SQL server using C# in ASP. NET
Not really understand what you want to realize, about excel operation you can try some free API for .NET.


这篇关于如何将Excel覆盖到C#?我有一个C#表单,我要在Excel文件中添加数据然后覆盖它这是我的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆