我已经实现了以下似乎工作正常的方法,但是它将文件保存到预定义的位置,而不是我希望它为用户提供一个选项,就像任何常规下载弹出窗口一样:打开,保存,另存为。任何的想法?
为了克服“在进行 OLE 调用之前必须将当前线程设置为单线程单元 (STA) 模式”异常,必须实现线程,请参阅编辑!
编辑:
1)
using System.Threading;
2)
[STAThread]
private static void ExportToExcel(DataTable dt)
{
Thread t = new Thread(SaveIt);
t.SetApartmentState(ApartmentState.STA);
t.Start(dt);
}
3)
static void SaveIt(Object dt)
{
DataTable table = (DataTable)dt;
System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
SaveName = sfd.FileName;
else
SaveName = "ResourceProfile";
workbook.SaveAs(.....
}
编辑结束。
private static void ExportToExcel(DataTable dt)
{
Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Application.Workbooks.Add(true);
int iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
excel.Cells[1, iCol] = c.ColumnName;
}
int iRow = 0;
foreach (DataRow r in dt.Rows)
{
iRow++;
// add each row's cell data...
iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
excel.Cells[iRow + 1, iCol] = r[c.ColumnName];
}
}
object missing = System.Reflection.Missing.Value;
DateTime CurrentDate = DateTime.Now;
String CurDate = CurrentDate.ToShortDateString().Replace("/",".");
workbook.SaveAs("ResourceProfile-" + CurDate + ".xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet, missing, missing, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
excel.Visible = true;
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet;
((Microsoft.Office.Interop.Excel._Worksheet)worksheet).Activate();
((Microsoft.Office.Interop.Excel._Application)excel).Quit();
}