我将多个数据表作为不同的工作表导出到单个 excel 文件中,并且工作正常。但是,excel 文件会保存到指定的路径。我想要一个另存为对话框,用户可以从中选择保存文件的路径。我在按钮单击时尝试了以下代码:
protected void excelexport(object sender, EventArgs e)
{
try
{
string sql = null;
string data = null;
string path = "C:\\inetpub/wwwroot/MahindraEarth/exportexcel/exportexcel";
int i = 0;
int j = 0;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
xlApp = new Excel.ApplicationClass();
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataTable dts = new System.Data.DataTable(); ;
System.Data.DataTable dss = new System.Data.DataTable();
Enquiry gs = new Enquiry();
ResultClass objres = gs.fn_GetEnquiryList();
if (objres.bStatus)
{
eslist<Enquiry> OBJLIST = objres.objData as eslist<Enquiry>;
if (OBJLIST.Count > 0)
{
dt = (DataTable)OBJLIST;
}
}
Operator op = new Operator();
ResultClass objrest = op.fn_GetOperatorList();
if (objrest.bStatus)
{
eslist<Operator> OBJLISTS = objrest.objData as eslist<Operator>;
if (OBJLISTS.Count > 0)
{
dts = (DataTable)OBJLISTS;
}
}
Contact co = new Contact();
ResultClass objress = co.fn_GetContactList();
if (objress.bStatus)
{
eslist<Contact> OBJLISS = objress.objData as eslist<Contact>;
if (OBJLISS.Count > 0)
{
dss = (DataTable)OBJLISS;
}
}
DataSet dataSet = new DataSet();
dataSet.Tables.Add(dt);
dataSet.Tables.Add(dts);
dataSet.Tables.Add(dss);
SaveFileDialog saveFileDialog = new SaveFileDialog();
String[] Worksheets = new String[dataSet.Tables.Count];
Excel.Worksheet[] xlWorkSheet = new Excel.Worksheet[dataSet.Tables.Count];
for (int k = 0; k < dataSet.Tables.Count; k++)
{
DataTable dst = dataSet.Tables[k];
xlWorkSheet[k] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(k + 1);
for (i = 0; i <= dst.Rows.Count - 1; i++)
{
for (j = 0; j <= dst.Columns.Count - 1; j++)
{
xlWorkSheet[k].Cells[1, j + 1] = dataSet.Tables[k].Columns[j].ColumnName;
data = dst.Rows[i].ItemArray[j].ToString();
xlWorkSheet[k].Cells[i + 2, j + 1] = data;
xlWorkSheet[k].Name = dataSet.Tables[k].TableName;
}
}
}
xlWorkBook.SaveAs(path + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
for (int p = 0; p < 3; p++)
{
releaseObject(xlWorkSheet[p]);
}
releaseObject(xlWorkBook);
releaseObject(xlApp);
exportsuccess.Style.Add("display", "");
}
catch (Exception ex)
{
}
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
}
finally
{
GC.Collect();
}
}
如何获取另存为对话框以便将多个数据表保存在多个工作表中而不是单个工作表中。
谢谢,