使用asp.net C#打开excel文件

时间:2016-04-13 06:06:00

标签: c# asp.net excel

我的要求是打开位于附件文件夹下的Excel文件。所以我从here获取了参考,并根据我的要求使用了 abatishchev 。所以我在下面的代码中试过了。

public void ExportExcel()
{
   string str_lwpc_query = string.Empty;
   str_lwpc_query = "select company_name 'COMPANY NAME',Deputed_Company_Name 'DEPUTED COMPANY NAME',emp_card_no 'EMP CODE',emp_name 'EMPLOYEE NAME',LWP,'' Remarks,  " +
                    "Adj_Days Gain_Loss_LOP_Days, VAL_DAY LOP_Days_Desc, month, year from XXACL_EMP_INFO_LWP_OTDAYS_HRS_V " +
                     "where emp_type='C' and month = '3' and year = '2015' ";
    DataTable Dt_lwpc = new DataTable();
    Dt_lwpc = CF.ExecuteDT(str_lwpc_query);
    DataSet DS_lwpc = new DataSet();
    DS_lwpc.Tables.Add(Dt_lwpc);
    DS_lwpc.Tables[0].TableName = "Employee loss of pay for consultant Details";
    var directory = Server.MapPath("~/Attachment/");
    ExcelLibrary.DataSetHelper.CreateWorkbook(directory + "Employee_lwpc_Details.xls", DS_lwpc);

    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
    ExcelLibrary.Office.Excel.Workbook wb = excel.Workbooks.Open(ExcelLibrary.DataSetHelper.CreateWorkbook(directory + "Employee_lwpc_Details.xls", DS_lwpc));
}

但我在最后一行收到错误

  

Microsoft.Office.Interop.Excel.Workbooks.Open(字符串,对象,对象,对象,...........)的最佳重载方法匹配有一些无效的参数

请提出错误的建议

2 个答案:

答案 0 :(得分:2)

如果您希望您网站的用户打开您在服务器上创建的Excel文件,而不是在那里打开它 - 只需将其发送给用户即可。用以下代码替换最后两行代码:

string filePath = directory + "Employee_lwpc_Details.xls"; 
Response.ContentType = "Application/vnd.ms-excel"; 
Response.AppendHeader("content-disposition", 
"attachment; filename=" + "Employee_lwpc_Details.xls"); 
Response.TransmitFile(filePath); 
Response.End();

答案 1 :(得分:0)

Microsoft.Office.Interop.Excel.Workbooks.Open采用文件名和一些其他参数see the MSDN documentation here.您正在调用的CreateWorkbook方法未返回Open的必需参数。