我正在编写用于在本地系统中下载excel文件的代码。
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbooks workBooks = excelApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workBook = workBooks.Open(@"D:\Myfile.xlsx");
// Microsoft.Office.Interop.Excel.Worksheet workSheet = workBook.Worksheets.get_Item(1);
workBook.SaveCopyAs(@"D:\Copy_Myfile.xlsx");
workBook.Close();
现在要求不是将文件保存到D盘,而是要求用户将文件保存到所需的位置。
有什么想法吗?
答案 0 :(得分:0)
public static void TransmitFile(Page CurrentPage, string FilePath)
// CurrentPage = this when called from CodeBehind
{
if (File.Exists(FilePath))
{
string FileName = Path.GetFileName(FilePath);
string Extension = Path.GetExtension(FilePath).ToLowerInvariant();
string ContentType;
switch (Extension)
{
case "xlsx":
ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
break;
case "xls":
ContentType = "application/vnd.ms-excel";
break;
case "csv":
ContentType = "text/csv";
break;
default:
ContentType = "application/octet-stream";
break;
}
if (CurrentPage != null)
{
CurrentPage.Response.ContentType = ContentType;
CurrentPage.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
CurrentPage.Response.TransmitFile(FilePath);
CurrentPage.Response.End();
}
else
throw new Exception("File transmission failed: cannot access current page");
}
else
throw new Exception("File transmission failed: file not found");
}