简体   繁体   English

在C#Win App中导出Excel数据

[英]Export excel data in C# win App

When export data, Excel file is empty! 导出数据时,Excel文件为空! I am beginner and I can't solve the problem. 我是初学者,无法解决问题。 This is my code: 这是我的代码:

Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
        Workbook wb = Excel.Workbooks.Add(XlSheetType.xlWorksheet);
        Worksheet ws = (Worksheet)Excel.ActiveSheet;
        Excel.Visible = true;


        ws.Cells[1, 1] = "Row";
        ws.Cells[1, 2] = "نام";
        ws.Cells[1, 3] = "نام خانوادگی";
        ws.Cells[1, 4] = "تاریخ ورود";
        ws.Cells[1, 5] = "تاریخ خروج";
        ws.Cells[1, 6] = "زمان ورود";
        ws.Cells[1, 7] = "زمان خروج";
        ws.Cells[1, 8] = "تاریخ فارسی";


        for(int j=2;j<=dataGridView1.Rows.Count; j++)
        {
            for(int i=2;i<=5;i++)
            {
                ws.Cells[j, 1] = dataGridView1.Rows[j - 2].Cells[i - 1].Value;
            }
        }

Result : Current Excel snapshot 结果: 当前Excel快照

Payam Hayati! Payam Hayati! You did not save the file or worksheet and that is why you did not get the desired output. 您没有保存文件或工作表,这就是为什么未获得所需输出的原因。 As an example, see the below: 例如,请参见以下内容:

public class Product
{
   public string Code { get; set; }
   public string Name { get; set; }
   public double Price { get; set; }
}

Above is a class to demonstrate how to save or export an excel file. 上面的类演示了如何保存或导出Excel文件。 Now we'll create a collection of objects as follows in a list: 现在,我们将在列表中创建对象集合,如下所示:

List<Product> products = new List<Product>()
{
  new Product { Code = "1234", Name = "Denim Jeans", Price = 2000 },
  new Product { Code = "123456", Name = "Denim Jacket", Price = 3000 },
  new Product { Code = "12345678", Name = "Nike Sneakers", Price = 4000 }
};

Now in a method, put the following code: (Remember to add reference of Microsoft.Office.Interop.Excel.dll ) 现在在一个方法中,输入以下代码:(记住要添加对Microsoft.Office.Interop.Excel.dll的引用)

public void ExportToExcel(List<Product> products)
{
  Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

  excel.Workbooks.Add();  //Create empty workbook
  Microsoft.Office.Interop.Excel._Worksheet workSheet = excel.ActiveSheet; //Create Worksheet from active sheet

  try
  {
    workSheet.Cells[1, "A"] = "Code"; //Set the header
    workSheet.Cells[1, "B"] = "Name";
    workSheet.Cells[1, "C"] = "Price";

    int row = 2; //Start the row
    foreach (Product items in products) //Iterate through a loop
    {
        workSheet.Cells[row, "A"] = items.Code;
        workSheet.Cells[row, "B"] = items.Name;
        workSheet.Cells[row, "C"] = string.Format("{0} Price", items.Price);

        row++;
    }

    workSheet.Range["A1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1);

    string fileName = string.Format(@"{0}\DatainExcel.xlsx", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));

    workSheet.SaveAs(fileName); //Save data in the file

    MessageBox.Show(string.Format("The file '{0}' is saved successfully!", fileName));
}

catch (Exception exception)
{
    MessageBox.Show("Exception", "Problem while saving Excel file!\n" + exception.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
}

finally
{
    excel.Quit(); //This is to quit excel

    if (excel != null)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);

    if (workSheet != null)

    System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);

    excel = null;
    workSheet = null;

    GC.Collect(); //This is to force garbage cleaning
  }
 }

And you are done. 您完成了。 Give a try. 试一下。

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

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