c#winform 如何导出excel

c#winform 如何导出excel引用了microsft excel 15.0 object library 无法使用microft.office命名空间,而且程序无法打开,提示任务失败,未找到aximp.exe,我office用的是2013

楼上导出的只是普通文本格式不是真正的excel文件,导出excel文件需要引用excel组件,在你的项目bin目录中右键选择引用找到类似Interop.Microsoft.Office.Interop.Excel.dll的文件引入进去,然后调用相关函数就可以了以下代码是我从我的项目中扣出来的,请自己改一下相关数据。usingMicrosoft.Office.Interop.Excel;GC.Collect();Applicationexcel;_WorkbookxBk;_WorksheetxSt;excel=newApplicationClass();xBk=excel.Workbooks.Add(true);xSt=(_Worksheet)xBk.ActiveSheet;////设置标题////设置标题excel.Cells[1,1]="姓名";excel.Cells[1,2]="身份证";xSt.get_Range(excel.Cells[1,1],excel.Cells[1,colCountStaff]).HorizontalAlignment=XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐for(inti=1;i<=rowCountStaff;i++){excel.Cells[i+1,1]="'"+listStaff[i-1].Name;excel.Cells[i+1,2]="'"+listStaff[i-1].CardNO;}for(inti=1;i<=rowCountCompany;i++){excel.Cells[i+1,5]="'"+listCompany[i-1].ID;excel.Cells[i+1,6]="'"+listCompany[i-1].Name;excel.Cells[i+1,7]="'"+listCompany[i-1].ParentID;}////显示效果////设置选中的部分的颜色xSt.get_Range(xSt.Cells[1,1],xSt.Cells[1,colCountStaff]).Select();xSt.get_Range(xSt.Cells[1,1],xSt.Cells[1,colCountStaff]).Interior.ColorIndex=19;//设置为浅黄色,共计有56种xSt.get_Range(xSt.Cells[1,1],xSt.Cells[rowCountStaff+1,colCountStaff]).Columns.AutoFit();//绘制边框xSt.get_Range(xSt.Cells[1,1],xSt.Cells[rowCountStaff+1,colCountStaff]).Borders.LineStyle=1;excel.Visible=false;stringfileName=DateTime.Now.ToString("yyyyMMddhhmmss");//设置导出文件的名称xBk.SaveCopyAs(Server.MapPath("~")+"\\Excel\\download\\"+fileName+".xls");//ds=null;xBk.Close(false,null,null);excel.Quit();System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);xBk=null;excel=null;xSt=null;GC.Collect();stringpath=Server.MapPath("~")+"\\Excel\\download\\"+fileName+".xls";System.IO.FileInfofile=newSystem.IO.FileInfo(path);Response.Clear();Response.Charset="GB2312";Response.ContentEncoding=System.Text.Encoding.UTF8;//添加头信息,为"文件下载/另存为"对话框指定默认文件名Response.AddHeader("Content-Disposition","attachment;filename="+Server.UrlEncode(file.Name));//添加头信息,指定文件大小,让浏览器能够显示下载进度Response.AddHeader("Content-Length",file.Length.ToString());//指定返回的是一个不能被客户端读取的流,必须被下载Response.ContentType="application/ms-excel";//把文件流发送到客户端Response.WriteFile(file.FullName);//停止页面的执行Response.End();追问

弄好了,谢谢

温馨提示:答案为网友推荐,仅供参考
相似回答