日期:2014-05-18  浏览次数:20726 次

asp.net 中 将List<Model> 型的数据导出到 excel,,急!!
asp.net 中 将List<Model> 型的数据导出到 excel,,急!!
在线等待中..........



------解决方案--------------------
楼主可以将list里的数据写到一个.csv的文件里,在这个文件里数据的格式为:
同一行里的数据用“,”分开就好了,例如:
1,2,3,4,5,6,
7,8,9,10,11,12,
------解决方案--------------------
一个一个的写csv文件还不如直接写xls好了. 可以写成个泛型,以后还能用.
------解决方案--------------------
C# code


        private void GenerateReport()
        {
            //Create Excel Application
            Excel._Application excelApp = new Excel.Application();
            Excel._Workbook excelFile;
            Excel._Worksheet sheetTrustee, sheetInsurer, sheetIssuer, sheetAcctDetail;
            
            //Get 3 spread sheets
            excelFile       = excelApp.Workbooks.Open(path, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true);

            sheetTrustee = (Excel._Worksheet)excelFile.Worksheets.get_Item(1);

    int i=0;
            List<MyModelClass> list = GetMyDataSource(); //获得你的Model List
            foreach(MyModelClass item in list)
            {
                //Insert new row in template
                ((Excel.Range)sheetTrustee.Cells[3+idx, 1]).EntireRow.Insert(Missing.Value);

                //Set values in new row
                sheetTrustee.Cells[i, 0] = item.UserName;
                sheetTrustee.Cells[i, 1] = item.XXX;
                sheetTrustee.Cells[i, 2] = item.????;
            }

            //Save & Close
            excelApp.DisplayAlerts = false;
            excelFile.Close(true, @"C:\filenamexxx", Missing.Value);
            excelApp.Quit();
        }

------解决方案--------------------
//输出到客户端
Response.AddHeader("Content-Disposition", "attachment; filename=Employee.xls" );
Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.Write( this.mString.ToString() ); // 把文件流发送到客户端
Response.End();

其中 mString为经过格式化的字符串,excel的字符格式如
内容\t内容\t\r\n
内容\t内容\t\r\n