简体   繁体   English

将 Datagridview 导出到现有的 Excel 文件 C#

[英]Export Datagridview to existing Excel file C#

i have a problem with my Software.我的软件有问题。 I want to export a Datagridview to an existing excel File.我想将 Datagridview 导出到现有的 excel 文件。 My software imports a excel file to a datagridview and now i want to do changes to the gridview and then safe it back.我的软件将一个 excel 文件导入到 datagridview 中,现在我想对 gridview 进行更改,然后将其安全返回。 I already tried a lot of options, but i want to add it into a existing file and the most tutorials are about how to export it into a new one.我已经尝试了很多选项,但我想将它添加到现有文件中,大多数教程都是关于如何将其导出到新文件中的。 Could anybody help me with my problem?有人可以帮我解决我的问题吗? I also had the idea of exporting the gridview to a new one and copy after that, the sheet of the new one into the existing one.我也有将 gridview 导出到一个新的想法,然后将新的工作表复制到现有的工作表中。 But same problem, i can´t find anything.但同样的问题,我找不到任何东西。 I´m very new to this whole programming thing and just a learnee in my company.我对这整个编程事情很陌生,只是我公司的一名学员。 It would be very great if someone could help me!如果有人可以帮助我,那就太好了! And sory if my english is bad, I live in Germany.如果我的英语不好,我住在德国。 Thank you:)谢谢:)

Remember to add in your reference (right click your project and choose CON reference and look for Microsoft Excel 15.0 obeject library)请记住添加您的参考(右键单击您的项目并选择 CON 参考并查找 Microsoft Excel 15.0 对象库)

private void btnExport_Click(object sender, EventArgs e)
{ 
    Microsoft.Office.Interop.Excel.Application xlworksheet = 
        new Microsoft.Office.Interop.Excel.Application();
           
    xlworksheet.Application.Workbooks.Open(
        @"C:\Users\BLANKSOASHEET.xlsx", 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);
           
    try
    {
       for(int i=1; i<DgvSOA.Columns.Count+1; i++)
       {
           worksheet.Cells[1,i] = datagridView1.Columns[i - 1].HeaderText;
       }       

       for (int i = 0; i < datagridView1.Rows.Count; i++)
       {
           for (int j = 0; j < datagridView1.Columns.Count; j++)
           {
                xlworksheet.Cells[i + 13, j + 1] = datagridView1.Rows[i].Cells[j].Value.ToString();
            }
        }
    }
}

This will save to a specific Excel file in a specific location.这将保存到特定位置的特定 Excel 文件。

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
            string sql = "SELECT * FROM Authors";
            SqlConnection connection = new SqlConnection(connectionString);
            SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
            DataSet ds = new DataSet();
            connection.Open();
            dataadapter.Fill(ds, "Authors_table");
            connection.Close();
            dataGridView1.DataSource = ds;
            dataGridView1.DataMember = "Authors_table";
        }

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

            Int16 i, j;

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);

            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            for (i = 0; i <= dataGridView1.RowCount - 2; i++)
            {
                for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
                {
                    xlWorkSheet.Cells[i + 1, j + 1] = dataGridView1[j, i].Value.ToString();
                }
            }

            xlWorkBook.SaveAs(@"c:\csharp.net-informations.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);
        }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM