如何将Datagridview内容导出到Excel-2010

问题描述:

大家好,

我正在寻找将datagridview内容导出到Excel-2010的最快方法.I

已经通过先将数据集转换为xml,然后转换为.xlsx来完成.但是找到了一些

解决方案中的问题.此方法最快吗?还是其他任何方法?

我将给出已经完成的代码


idssTableDataSet.WriteXml("D:\\ Customers.xml");


Microsoft.Office.Interop.Excel.Application APexcel = null;
Microsoft.Office.Interop.Excel.Workbook MyBook = null;
Microsoft.Office.Interop.Excel.Worksheet MySheet = null;


APexcel =新的Microsoft.Office.Interop.Excel.Application();
APexcel.Visible = false;
MyBook = APexcel.Workbooks.Open("D:\\ Customers.xml",Type.Missing,true,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type. Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
MySheet =(Microsoft.Office.Interop.Excel.Worksheet)MyBook.ActiveSheet;
MyBook.SaveAs("D:\\ Customers.xlsx",Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,null,null,false,false,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,false,false, null,null,null);


保存.xlsx文件后,显示错误消息我无法打开文件,因为文件格式或扩展名无效.请验证文件未损坏且文件扩展名与文件格式匹配"打开.xlsx文件.请帮助我.

在此先感谢

Hi all,

I am looking for a fastest way for exporting datagridview content to Excel-2010.I

have already done by converting first dataset to xml then to .xlsx.But finding some

issues in this solution.Is this method is fastest?Or any other method?

I will give the code what I have already done


idssTableDataSet.WriteXml("D:\\Customers.xml");


Microsoft.Office.Interop.Excel.Application APexcel = null;
Microsoft.Office.Interop.Excel.Workbook MyBook = null;
Microsoft.Office.Interop.Excel.Worksheet MySheet = null;


APexcel = new Microsoft.Office.Interop.Excel.Application();
APexcel.Visible = false;
MyBook = APexcel.Workbooks.Open("D:\\Customers.xml", Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
MySheet = (Microsoft.Office.Interop.Excel.Worksheet)MyBook.ActiveSheet;
MyBook.SaveAs("D:\\Customers.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, false, false, null, null, null);


After saving the .xlsx file it is showing an error that "Excel cannot open the file because the file format or extension is not valid.Verify that the file has not been corrupted and the file extension matches the format of the file" when I am opening the .xlsx file.Please help me.

Thanks in advance

看看这个例子,可能会有所帮助.

如何将DataGridView导出到Excel文件
Have a look at this exampel, it might help.

How to export DataGridView to excel file