日期:2014-05-18 浏览次数:20825 次
public static void SaveAs(DataGridView gridView) { //导出到execl try { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "导出Excel (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; //saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "导出Excel格式文档"; saveFileDialog.ShowDialog(); string strName = saveFileDialog.FileName; if (strName.Length != 0) { //toolStripProgressBar1.Visible = true; //以下变量什么意思? System.Reflection.Missing miss = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); excel.Application.Workbooks.Add(true); excel.Visible = false;//若是true,则在导出的时候会显示EXcel界面 //excel.Visible = true; if (excel == null) { MessageBox.Show("EXCEL无法启动!(可能您没有安装EXCEL,或者版本与本程序不符)","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); return; } Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks; Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss)); Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet; sheet.Name = "数据"; //int m = 0, n = 0; //添加表头 for (int i = 0; i < gridView.ColumnCount; i++) { excel.Cells[1, i+1] = gridView.Columns[i].HeaderText.ToString(); } //填充数据 for (int i = 0; i < gridView.RowCount; i++) { //i为行,j为列 for (int j = 0; j < gridView.ColumnCount; j++) { ////注意:datagrid的引用方法是 datagrid1[列,行],即先列后行 if (gridView[j, i].Value.GetType() == typeof(string)) { //MessageBox.Show(gridView[j, i].Value.ToString()); excel.Cells[i + 2, j + 1] = "'" + gridView[j, i].Value.ToString(); } else { excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString(); } } //toolStripProgressBar1.Value += 100 / gridView.RowCount; } sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss); //book.Close(false, miss, miss); //books.Close(); //excel.Quit(); //System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet); //System.Runtime.InteropServices.Marshal.ReleaseComObject(book); //System.Runtime.InteropServices.