溫馨提示×

  • 首頁 > 
  • 問答 > 
  • 編程語言  > 
  • C# 點(diǎn)擊導(dǎo)出按鈕GridView導(dǎo)出到Excel時(shí)不彈出打開或保存對

C# 點(diǎn)擊導(dǎo)出按鈕GridView導(dǎo)出到Excel時(shí)不彈出打開或保存對

小億
121
2023-12-20 14:42:12
欄目: 編程語言

要在C#中實(shí)現(xiàn)點(diǎn)擊導(dǎo)出按鈕GridView導(dǎo)出到Excel時(shí)不彈出打開或保存對話框,可以使用以下步驟:
1. 添加對`Microsoft.Office.Interop.Excel`和`System.Reflection`的引用。
2. 在按鈕的點(diǎn)擊事件處理程序中編寫導(dǎo)出邏輯。

private void ExportToExcel_Click(object sender, EventArgs e)
{

????//?創(chuàng)建Excel對象

????Microsoft.Office.Interop.Excel.Application?excel?=?new?Microsoft.Office.Interop.Excel.

????Application();

????Microsoft.Office.Interop.Excel.Workbook?workbook?=?excel.Workbooks.Add(Type.Missing);

????Microsoft.Office.Interop.Excel.Worksheet?worksheet?=?null;

????try

????{

????????//?設(shè)置工作表

????????worksheet?=?workbook.ActiveSheet;

????????//?填充數(shù)據(jù)到工作表

????????for?(int?i?=?0;?i?<?gridView.Rows.Count;?i++)

????????{

????????????for?(int?j?=?0;?j?<?gridView.Columns.Count;?j++)

????????????{

????????????????worksheet.Cells[i?+?1,?j?+?1]?=?gridView.Rows[i].Cells[j].Value.ToString();

????????????}

????????}

????????//?保存Excel文件

????????workbook.SaveAs(“YourFilePath.xlsx”,?Microsoft.Office.Interop.Excel.XlFileFormat.

????????xlOpenXMLWorkbook,?Type.Missing,?Type.Missing,?false,?false,?Microsoft.Office.Interop.Excel.

????????XlSaveAsAccessMode.xlNoChange,?Type.Missing,?Type.Missing,?Type.Missing,?Type.Missing,?

????????Type.Missing);

????????workbook.Close();

????????excel.Quit();

????????//?釋放資源

????????System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);

????????System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);

????????System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);

????????MessageBox.Show(“導(dǎo)出成功!”);

????}

????catch?(Exception?ex)

????{

????????MessageBox.Show(“導(dǎo)出失?。骸?+?ex.Message);

????}

????finally

????{

????????//?釋放Excel進(jìn)程

????????worksheet?=?null;

????????workbook?=?null;

????????excel?=?null;

????????GC.Collect();

????} }

請注意,這種方法將直接保存Excel文件到指定路徑,而不會彈出打開或保存對話框。確保將"YourFilePath.xlsx"替換為您要保存的實(shí)際文件路徑。

0