我使用以下方法从数据库导出excel文件。但是我在导出excel文件时有一个问题,而不是自动下载到下载文件夹,我不希望这种情况发生,我想要我的excel文件可以在我的项目文件夹中下载
var formsection = from fs in db.FormSections
join form in Form on fs.FormId equals form.FormId
select fs;
XLWorkbook wb = new XLWorkbook();
string sheetName = "ARTICLE"; //Give name for export file.
var Fs = wb.Worksheets.Add("FORMSECTION");
Fs.Cell(2, 1).InsertTable(formsection.ToList());// assign list here.
HttpContext.Response.Clear();
HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx", sheetName.Replace(" ", "_")));
var filePath = Path.Combine(Server.MapPath("~/Content"));
using (MemoryStream memoryStream = new MemoryStream())
{
wb.SaveAs(memoryStream);
memoryStream.WriteTo(HttpContext.Response.OutputStream);
memoryStream.Close();
}
HttpContext.Response.End();
答案 0 :(得分:2)
这是一个将数据表转换为.csv文件并将文件保存到项目文件夹的示例,它将文件存储在Domestic文件夹中作为我给出的路径。
private void test(DataTable dt1) {
string csv = string.Empty;
foreach (DataColumn column in dt1.Columns)
{
//Add the Header row for CSV file.
csv += column.ColumnName + ',';
}
//Add new line.
csv += "\r\n";
foreach (DataRow row in dt1.Rows)
{
foreach (DataColumn column in dt1.Columns)
{
//Add the Data rows.
csv += row[column.ColumnName].ToString().Replace(",", ";") +',';
}
//Add new line.
csv += "\r\n";
}
string datetime = Convert.ToString(DateTime.Today.ToString("dd-MM-yyyy")).Trim();
string filepath = "C:\\Users\\Prateek\\Desktop\\MMR New 27-07 -\\Domestic\\";
string filename= @"BILLING_BOOK_NO" + "_4005" + "_"+datetime+".CSV";
string combinepath = filepath + filename;
System.IO.File.WriteAllText(combinepath,csv);
}`
答案 1 :(得分:1)
您需要先将excel写入服务器。
wb.SaveAs(filePath);
//encrypt the file
Encrypt(filePath);
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (MemoryStream memoryStream = new MemoryStream())
{
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
memoryStream.Write(bytes, 0, (int)file.Length);
memoryStream.WriteTo(HttpContext.Response.OutputStream);
}
}
答案 2 :(得分:0)
使用以下代码
public void ImportXLX()
{
string filePath = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), @"C:\Users\Vipin\Desktop\Sheets\MyXL6.xlsx");
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath);
Request.Files["xlsFile"].SaveAs(filePath);
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
}