简体   繁体   English

导出并保存datagridview Excel 或 Txt 带按钮

[英]Export and save the datagridview Excel or Txt With a button

I want to save a datagridview as a different excel or txt file every time I click the save button with using c#.每次使用 c# 单击保存按钮时,我想将 datagridview 保存为不同的 excel 或 txt 文件。 How can I do that我怎样才能做到这一点

Here is my codes.这是我的代码。 But it isn't working as I want.但它没有按我的意愿工作。

private void button5_Click(object sender, EventArgs e)
    {
        //This line of code creates a text file for the data export.
        System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\\Users\DiktaşHaftalikUretim\\table.txt");
        try
        {
            string sLine = "";

            //This for loop loops through each row in the table
            for (int r = 0; r <= dataGridView2.Rows.Count - 1; r++)
            {
                //This for loop loops through each column, and the row number
                //is passed from the for loop above.
                for (int c = 0; c <= dataGridView2.Columns.Count - 1; c++)
                {
                    sLine = sLine + dataGridView2.Rows[r].Cells[c].Value;
                    if (c != dataGridView2.Columns.Count - 1)
                    {
                        //A comma is added as a text delimiter in order
                        //to separate each field in the text file.
                        //You can choose another character as a delimiter.
                        sLine = sLine + ",";
                    }
                }
                //The exported text is written to the text file, one line at a time.
                file.WriteLine(sLine);
                sLine = "";
            }

            file.Close();
            System.Windows.Forms.MessageBox.Show("Export Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (System.Exception err)
        {
            System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            file.Close();
        }

    }

I am using interop.我正在使用互操作。 First you need to add refercnce to interop excel, if you dont have already you need to download from Nuget.首先,您需要添加对互操作 excel 的引用,如果您还没有,则需要从 Nuget 下载。

在此处输入图像描述

  private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            // creating Excel Application  
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            // creating new WorkBook within Excel application  
            Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
            // creating new Excelsheet in workbook  
            Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
            worksheet = workbook.ActiveSheet;
            // changing the name of active sheet  
            worksheet.Name = "Test";
            // storing header part in Excel  
            for (int i = 1; i < dgvData.Columns.Count + 1; i++)
            {
                worksheet.Cells[1, i] = dgvData.Columns[i - 1].HeaderText;
            }
            // storing Each row and column value to excel sheet  
            for (int i = 0; i < dgvData.Rows.Count - 1; i++)
            {
                for (int j = 0; j < dgvData.Columns.Count; j++)
                {
                    worksheet.Cells[i + 2, j + 1] = dgvData.Rows[i].Cells[j].Value.ToString();
                }
            }
            // save the application  
            workbook.SaveAs("YOUR_PATH\\Test.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
       false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
       Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            // Exit from the application  
            app.Quit();
        }
        catch (Exception ex)
        {

        }
    }

Notice: if you want to open excel file right after you transfer the data delete the line app.Quit();注意:如果要在传输数据后立即打开 excel 文件,请删除行 app.Quit(); and add app.Visible = true;并添加 app.Visible = true;

and the result:结果:

在此处输入图像描述

在此处输入图像描述

If saving to Excel is .xlsx format, consider using SpreadSheetLight which is added via NuGet package manager in Visual Studio.如果保存到 Excel 是.xlsx格式,请考虑使用通过 Visual Studio 中的 NuGet package管理器添加的 SpreadSheetLight。

  • This example has a DateTime column which needs a style, if you do not have a DateTime column ignore this.此示例有一个需要样式的 DateTime 列,如果您没有 DateTime 列,请忽略它。
  • After the data is imported, started at A1 the columns are auto-sized导入数据后,从 A1 开始,列自动调整大小
  • Use document.RenameWorksheet(SLDocument.DefaultFirstSheetName,"TODO");使用document.RenameWorksheet(SLDocument.DefaultFirstSheetName,"TODO"); before SaveAs to rename the default WorkSheet.在 SaveAs 之前重命名默认工作表。

Add this class to your project将此 class 添加到您的项目中

using SpreadsheetLight;
using System;
using System.Data;

namespace Demo.Classes
{
    internal class ExcelOperations
    {
        /// <summary>
        /// Save <see cref="DataTable"/> to an Excel file, in this case the 4th column is a Date so we
        /// need to format this column using a <see cref="SLStyle"/>
        /// <para></para>
        /// The data will start at A1
        /// <para></para>
        /// For the caller var (success, exception) = ExcelOperations.Export(dt, "SomeFile.xlsx");
        /// </summary>
        /// <param name="table">DataTable to import into a new Excel file</param>
        /// <param name="fileName">File name to save data</param>
        /// <returns>
        /// Success and Exception
        /// <para></para>
        /// When no errors, success is true and exception will be null, if not success, exception will
        /// contain the runtime exception
        /// </returns>
        public static (bool success, Exception exception) Export(DataTable table, string fileName)
        {
            try
            {
                using (var document = new SLDocument())
                {
                    SLStyle dateStyle = document.CreateStyle();
                    dateStyle.FormatCode = "mm-dd-yyyy";

                    // start at A1
                    document.ImportDataTable(1, SLConvert.ToColumnIndex("A"), table, true);

                    document.SetColumnStyle(4, dateStyle);
                    
                    // auto size columns
                    var stats = document.GetWorksheetStatistics();
                    for (int index = 0; index < stats.EndColumnIndex +1; index++)
                    {
                        document.AutoFitColumn(index);
                    }

                    document.SaveAs(fileName);

                    return (true, null);
                }
            }
            catch (Exception exception)
            {
                return (false, exception);
            }
        }
    }
}

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

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