要在C#中實現點擊導出按鈕GridView導出到Excel時不彈出打開或保存對話框,可以使用以下步驟:
1. 添加對`Microsoft.Office.Interop.Excel`和`System.Reflection`的引用。
2. 在按鈕的點擊事件處理程序中編寫導出邏輯。
private void ExportToExcel_Click(object sender, EventArgs e) {????//?創建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
????{
????????//?設置工作表
????????worksheet?=?workbook.ActiveSheet;
????????//?填充數據到工作表
????????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(“導出成功!”);
????}
????catch?(Exception?ex)
????{
????????MessageBox.Show(“導出失敗:”?+?ex.Message);
????}
????finally
????{
????????//?釋放Excel進程
????????worksheet?=?null;
????????workbook?=?null;
????????excel?=?null;
????????GC.Collect();
????} }
請注意,這種方法將直接保存Excel文件到指定路徑,而不會彈出打開或保存對話框。確保將"YourFilePath.xlsx"替換為您要保存的實際文件路徑。