C#导出Excel文件

1.首先介绍用到的命名空间

System

System.Web

System.Web.Mvc

System.IO

System.Threading

2.相关知识点:

2_1:Server.MapPath() 和 Request.MapPath()使用区别:

      /根目录       ./当前目录        ../上层目录(相对当前目录) ,
    (如果当前的网站目录为D:\wwwroot, 浏览的页面路径为D:\wwwroot\company\user\index.asp )
在index.asp页面中使用:

Server.MapPath("/")    返回路径为:D:\wwwroot 
Server.MapPath("./")   返回路径为:D:\wwwroot\company\user
Server.MapPath("../")   返回路径为:D:\wwwroot\company 

2_2:调用示例:
    (1)server.MapPath(request.ServerVariables("Path_Info1")) 
    (2)Request.ServerVariables("Path_Info2")   
             返回路径: D:\wwwroot\company\user\index.asp 
2_3:映射路径问题:
Server.MapPath(string)   :是将相对于当前调用文件的文件(或目录)映射为物理路径; 
Request.MapPath(string) :是将string虚拟路径映射为物理路径
           Server.MapPath(string) 中string 可以用“../”方式引用父目录,甚至可以将此目录跳到整个WEB目录外,如:C:\WWWROOT ,目录为WEB根目录,在根目录文件中调用此Server.MapPath("../1234567890.jpg"),则可以调用WEB目录外的脚本、资源等。 
           Request.MapPath(string) 中的string为虚拟目录,只能相对WEB虚拟目录形式的,也不允许"../"方式调用,只能是"/","/xx"等字符串 ,如string dirUpload = Request.MapPath("~/Export");
           实际使用中,有时候直接用Server.MapPath(string) 调用一个文件比较麻烦,因为不同的目录中调用同一个Server.MapPath(string) 函数就会得到不同的值, 特殊的话,就需要通过判断本身目录层次才能获取正确的地址,使用的Request.MapPath(string)就可以调用同一个目录文件,不用做目录判断

3.一个实例

(1)获取到导出的数据

 //导出框架
        public FileResult InfoToExcel(传参数)
        { 
           //1.获取所有信息           
            ManageService test= new ManageService();
            var list = test.Get_ForExcel11(传参数);  
           //2.定义导出的文件名字        
            string fileName = string.Format("{0}_{1}_信息表.xls", year,mouth);
           //3.定义导出的虚拟路径
            string Upload = Request.MapPath("~/Export");
            //4.检查导出目录,没有就创建
            if (!Directory.Exists(Upload))
            {
                Directory.CreateDirectory(Upload);
            }
            //5.合并导出路径
            string Sub = Path.Combine(Upload, Guid.NewGuid().ToString());
            if (!Directory.Exists(Sub))
            {
                Directory.CreateDirectory(Sub);
            }
            string filePath = Path.Combine(Sub, fileName);
            //6.导出
            bool result = etms.Export_InfoForExcel(list, filePath);
            //记录到日志中          
            string msg = string.Format("管理信息-》导出");
            CommonLib.Common.SaveInfoLog(string.Format("[导出]-Type[{0}]-UserId[{1}]:{2}", type, uid, msg));
            //File()3个参数,fileName,contentType,fileDownloadName
            return File(filePath, "application/ms-excel", fileName);
        }

(2)具体导出方法:


        public bool Export_InfoForExcel(IList<Info> list, string fileName)
        {
            int i = 0;
            int j = 0;
            int dataIndex = 1;
            //工作簿
            ISheet sheet = null;
            IWorkbook workbook = null;
           //FileStream()3个参数,path,fileMode,fileAcces
            FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            try
            {
                // 2007版本
                if (fileName.IndexOf(".xlsx") > 0)
                {
                    throw new Exception("不支持2007及以上版本的excel文件。");
                }
                // 2003版本
                else if (fileName.IndexOf(".xls") > 0) 
                {
                    workbook = new HSSFWorkbook();
                }
                if (workbook != null)
                {
                    sheet = workbook.CreateSheet("违纪信息");
                }
                else
                {
                    return false;
                }
                string[] columeNameList = { "one", "two", "three"};             
                IRow rowHead = sheet.CreateRow(0);
                for (j = 0; j < columeNameList .Length; ++j)
                {
                    rowHead.CreateCell(j).SetCellValue(columeNameList [j]);
                }

                for (i = 0; i < list.Count; ++i)
                {
                    IRow row = sheet.CreateRow(dataIndex);
                    row.CreateCell(0).SetCellValue(list[i].one);
                    row.CreateCell(1).SetCellValue(list[i].two);
                    row.CreateCell(2).SetCellValue(list[i].three);
                    ++dataIndex;
                }
                //写入到excel
                workbook.Write(fs); 
                fs.Dispose();
                return true;
            }
            catch (Exception ex)
            {
                fs.Dispose();
                Common.SaveErrorLog(ex.Message);
                return false;
            }
        }

猜你喜欢

转载自my.oschina.net/u/3544533/blog/1802085