public bool ExportDataGridview(DataGridView gridView, bool isShowExcle) { if (gridView.Rows.Count == 0) { return false; } //建立Excel物件 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); excel.Application.Workbooks.Add(true); //生成欄位名稱 for (int i = 0; i < gridView.ColumnCount;i++) { excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText; } //填充資料 for (int i = 0; i < gridView.RowCount - 1; i++) //迴圈行 { for(int j = 0;j < gridView.ColumnCount ;j++) //迴圈列 { if(gridView[j,i].ValueType==typeof(string)) { excel.Cells[i+2,j+1] = """ + gridView.Rows[i].Cells[j].Value.ToString(); } else { excel.Cells[i+2,j+1] = gridView.Rows[i].Cells[j].Value.ToString(); } } } //設定禁止彈出儲存和覆蓋的詢問提示框 excel.Visible = false; excel.DisplayAlerts = false; excel.AlertBeforeOverwriting = false; //儲存到臨時工作簿 //excel.Application.Workbooks.Add(true).Save(); //儲存檔案 excel.Save("D:" + "\\234.xls"); excel.Quit(); return true; }
解決方案及資源管理器裡面有個引用,你新增一下就可以了
public bool ExportDataGridview(DataGridView gridView, bool isShowExcle) { if (gridView.Rows.Count == 0) { return false; } //建立Excel物件 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); excel.Application.Workbooks.Add(true); //生成欄位名稱 for (int i = 0; i < gridView.ColumnCount;i++) { excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText; } //填充資料 for (int i = 0; i < gridView.RowCount - 1; i++) //迴圈行 { for(int j = 0;j < gridView.ColumnCount ;j++) //迴圈列 { if(gridView[j,i].ValueType==typeof(string)) { excel.Cells[i+2,j+1] = """ + gridView.Rows[i].Cells[j].Value.ToString(); } else { excel.Cells[i+2,j+1] = gridView.Rows[i].Cells[j].Value.ToString(); } } } //設定禁止彈出儲存和覆蓋的詢問提示框 excel.Visible = false; excel.DisplayAlerts = false; excel.AlertBeforeOverwriting = false; //儲存到臨時工作簿 //excel.Application.Workbooks.Add(true).Save(); //儲存檔案 excel.Save("D:" + "\\234.xls"); excel.Quit(); return true; }
解決方案及資源管理器裡面有個引用,你新增一下就可以了