代码如下:
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel文件(*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出文件保存路径";
saveFileDialog.FileName = fileName;
saveFileDialog.ShowDialog();
string strName = saveFileDialog.FileName;
if (strName.Length != 0)
{
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界面。
if (excel == null)
{
MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
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 = "Sheet1";
int colIndex = 0;
int RowIndex = 1;
//开始写入每列的标题
foreach (DataColumn dc in dtColumn.Columns)
{
colIndex++;
excel.Cells[RowIndex, colIndex] = dc.Caption;
}
//开始写入内容
int RowCount = dtColumn.Rows.Count;//行数
for (int i = 0; i < RowCount; i++)
{
RowIndex++;
int ColCount = dtColumn.Columns.Count;//列数
for (colIndex = 1; colIndex <= ColCount; colIndex++)
{
excel.Cells[RowIndex, colIndex] = dtColumn.Rows[i][colIndex - 1];
}
}
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.Marshal.ReleaseComObject(books);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
GC.Collect();
你的计算机上是不是安装了office 2007了?如果是的话,他会保存成*.xlsx
一般我们在导出excel的时候都是保存成 *.xls 的方便兼容问题 找了一些解决方案 最后公司同事给的一个建议和资料参考 问题很简显得很简单 一般我们写连接串的时候都会写成 Provider = Microsoft.Jet.OLEDB.4.0 ;Persist Security Info=False; Data Source = " + filePath + ";Extended Properties=Excel 8.0;" 过于老了一点很难去兼容Excel版本问题
可尝试使用 Provider = Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;Data Source= " + filePath + ";Extended Properties=Excel 8.0;" 还没来的急看看具体区别。