在线等——dataTable数据导出到Excel文件,怎么实现选择保存路径?
实现一个SQL查询出来的数据导入到Excel文件,功能是实现,可是有个问题就是我的路径是写死的,怎么实现让用户选择保存路径 代码贴出如下:
//数据导出
private void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)
{
if (tmpDataTable == null)
{
return;
}
int rowNum = tmpDataTable.Rows.Count;
int columnNum = tmpDataTable.Columns.Count;
int rowIndex = 1;
int columnIndex = 0;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xlApp.DefaultFilePath = "D:\";
xlApp.DisplayAlerts = true;
xlApp.SheetsInNewWorkbook = 1;
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
//将DataTable的列名导入Excel表第一行
foreach (DataColumn dc in tmpDataTable.Columns)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
}
//将DataTable中的数据导入Excel中
for (int i = 0; i < rowNum; i++)
{
rowIndex++;
columnIndex = 0;
for (int j = 0; j < columnNum; j++)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();
}
}
xlBook.SaveCopyAs(strFileName + ".xls");
}
private void SaveFileDialog()
{
//string localFilePath, fileNameExt, newFileName, FilePath;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//设置文件类型
saveFileDialog1.Filter = " excel files(*.xls)
[其他解释]protected void btnPrint_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Order.xls");
Response.Charset = "gb2312";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.AllowPaging = false;
Bin();
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
GridView1.AllowPaging = true;
Bin();
}
或许对你有帮助
[其他解释]