public void ExportExcel(string saveFileName, DataGridView myDGV) { Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) { MessageBox.Show("No Excel on this machine!"); return; } Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; // Write title for (int i = 0; i < myDGV.ColumnCount; i++) { worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText; } //Write data for (int r = 0; r < myDGV.Rows.Count; r++) { for (int i = 0; i < myDGV.ColumnCount; i++) { worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value; } System.Windows.Forms.Application.DoEvents(); } worksheet.Columns.EntireColumn.AutoFit(); if (saveFileName != "") { try { workbook.Saved = true; workbook.SaveCopyAs(saveFileName); } catch (Exception ex) { MessageBox.Show("The file is occupied " + ex.Message); return; } } xlApp.Quit(); GC.Collect(); } private void btExport_Click(object sender, EventArgs e) { ExportExcel(@"D:/test.xls", dgvTestDeck); }
或着,
private void button1_Click(object sender, EventArgs e) { copyAlltoClipboard(); Microsoft.Office.Interop.Excel.Application xlexcel; Microsoft.Office.Interop.Excel.Workbook xlWorkBook; Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; // Reset the row header dgvTest.RowHeadersVisible = true; xlexcel = new Microsoft.Office.Interop.Excel.Application(); xlexcel.Visible = true; xlWorkBook = xlexcel.Workbooks.Add(misValue); xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1]; CR.Select(); xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true); // Deselect the datagridview table foreach (DataGridViewRow dr in dgvTest.SelectedRows) { dr.Selected = false; } } private void copyAlltoClipboard() { // move the row header dgvTest.RowHeadersVisible = false; dgvTest.SelectAll(); dgvTest.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText; DataObject dataObj = dgvTest.GetClipboardContent(); if (dataObj != null) Clipboard.SetDataObject(dataObj); }