我有这个导出功能,允许我将2个网格视图导出到一个excel中的2个单独的工作表中 .
但我的问题是:
-
当我点击导出按钮提示用户打开,保存为,取消下载而不是将其保存到特定位置(目前我在我的代码中执行的操作)时,如何拥有常规下载的常用弹出窗口?
-
如何为所有单元格设置代码以启用wraptext = true,并自动格式化列高度和宽度以固定所有文本,以便在列宽度时不显示日期######作为示例打开excel时太小 .
protected void EXPORT_BUTTON_Click(object sender,EventArgs e){Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application(); //在Excel应用程序中创建新的WorkBook Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
String DT1 = "Data table 1";
String DT2 = "Data table 2";
ExportToExcel(app, workbook, Gridview1, DT1, 1);
ExportToExcel(app, workbook, Gridview2, DT2, 2);
}
public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName, int sheetid)
{
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = (Excel.Worksheet)workbook,Worksheets.Add();
// changing the name of active sheet
worksheet.Name = SheetName;
// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
}
}
//save the application
workbook.SaveAs(@"C:\Users\test\Desktop\Test\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
}
4 回答
试试这个:
修改excel文件的路径以保存到虚拟路径,如下所示
将此更改为
请尝试以下代码以显示另存为对话框
由Laxmikant指定修改方法“ExportToExcel”的代码如下 .
我删除了这两行代码,现在不需要参数“Sheetid”
希望这能解决您的问题
您尚未在工作簿中添加工作表
尝试以下代码
worksheet =(Excel._Worksheet)oXL.Worksheets.Add();
worksheet.Name = SheetName;
了解更多信息,请查看http://dotnetmentors.com/c-sharp/how-to-export-sql-data-to-excel-using-microsoft-office-interop.aspx
使用rang设置 Headers