主要是见过很多导出的列子,而看后每一个都不够完善。自己弄一个暂时觉得没问题的
TimeSpan dateBegin = new TimeSpan(DateTime.Now.Ticks); SaveFileDialog sf = new SaveFileDialog(); sf.Filter = "导出Excel(*.xls)|*.xls"; sf.FileName = "导入失数据";//初始化导出excel名称 if (sf.ShowDialog() == DialogResult.OK) { try { string strName = sf.FileName; if (strName.Length != 0) { System.Reflection.Missing miss = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); excel.Application.Workbooks.Add(true); excel.Visible = false; if (excel == null) { MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } 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 = "Sheet";//工作薄名称 //填充列头 for (int i = 0; i < newDt.Columns.Count; i++) { excel.Cells[1, i + 1] = newDt.Columns[i].ColumnName; } //填充数据 for (int row = 0; row <= newDt.Rows.Count - 1; row++) { for (int column = 0; column < newDt.Columns.Count; column++) { if (newDt.Rows[row][column].GetType() == typeof(string)) { excel.Cells[row + 2, column + 1] = "'" + newDt.Rows[row][column].ToString(); } else { excel.Cells[row + 2, column + 1] = newDt.Rows[row][column].ToString(); } } } string Version = excel.Version;//获取本机的Excel格式 int FormatNum; if (Convert.ToDouble(Version) < 12)//表示97-2003格式 { FormatNum = -4143; } else//007以后的excel版本 { FormatNum = 56; } sheet.SaveAs(strName, FormatNum, 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.Marshal.ReleaseComObject(books); System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); GC.Collect();//对未使用内存的服务进行回收 XtraMessageBox.Show("导出成功!"); } } catch (Exception ex) { XtraMessageBox.Show("导出失败!"); System.GC.Collect(); } }
浙公网安备 33010602011771号