C# export Excel file

1. First introduce the namespaces used

System

System.Web

System.Web.Mvc

System.IO

System.Threading

2. Relevant knowledge points:

2_1: The difference between Server.MapPath() and Request.MapPath():

      /root directory ./current directory ../upper directory (relative to the current directory),
    (if the current website directory is D:\wwwroot, the browsed page path is D:\wwwroot\company\user\index.asp )
in index .asp pages use:

Server.MapPath("/") The return path is: D:\wwwroot 
Server.MapPath("./") The return path is: D:\wwwroot\company\user
Server.MapPath("../") The return path is :D:\wwwroot\company 

2_2: Call example:
    (1) server.MapPath(request.ServerVariables("Path_Info1")) 
    (2) Request.ServerVariables("Path_Info2")   
             Return path: D:\wwwroot\company\user\index.asp 
2_3: Map Path problem:
Server.MapPath(string) : Map the file (or directory) relative to the currently called file to a physical path; 
Request.MapPath(string) : Map the string virtual path to a physical path
           Server.MapPath(string) In the string, you can use "../" to refer to the parent directory, and you can even jump this directory to the entire WEB directory, such as: C:\WWWROOT, the directory is the WEB root directory, and call this Server.MapPath( "../1234567890.jpg"), you can call scripts, resources, etc. outside the WEB directory. 
           The string in Request.MapPath(string) is a virtual directory, which can only be in the form of a relative WEB virtual directory, and does not allow "../" to be called. It can only be strings such as "/", "/xx", such as string dirUpload = Request.MapPath("~/Export");
           In actual use, sometimes it is troublesome to call a file directly with Server.MapPath(string), because calling the same Server.MapPath(string) function in different directories will get different values. In special cases, you need to pass the judgment itself. The correct address can be obtained only by the directory level, and the same directory file can be called by using Request.MapPath(string) without making a directory judgment.

3. An instance

(1) Obtain the exported data

 //导出框架
        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) The specific export method:


        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;
            }
        }

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324945587&siteId=291194637