C# List .NET MVC导出数据到EXCEL或者CSV文件

       

C#导出数据到 CSV文件:

      

  /// <summary>
        /// 获取类的属性集合(以便生成CSV文件的所有Column标题):
        /// </summary>
        /// <returns></returns>
        private PropertyInfo[] GetPropertyInfoArray<T>()
        {
            PropertyInfo[] props = null;
            try
            {
                Type type = typeof(T);
                object obj = Activator.CreateInstance(type);
                props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            }
            catch (Exception)
            { }
            return props;
        }

 /// <summary>
        /// 导出角色信息
        /// </summary>
        /// <param name="List">传过来的一个list集合</param>
        /// <param name="filePath">文件完整路径(包括文件名和后缀)</param>
        /// <returns></returns>
        public bool SaveDataToCSVFileRole(List<RoleBF> List, string filePath)
        {
            bool successFlag = true;
            StringBuilder strColumn = new StringBuilder();
            StringBuilder strValue = new StringBuilder();
            StreamWriter sw = null;
            FileStream fs = null;
            PropertyInfo[] props = GetPropertyInfoArray<RoleBF>();

            try
            {
                fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);//文件流
                sw = new StreamWriter(fs, System.Text.Encoding.Default);//写文件。注意System.Text.Encoding.Default是获取本机编码方式,可自己指定。读取的时候得相同编码方式否则会有乱码。

//写入头部开始
                for (int i = 0; i < props.Length; i++)
                {
                    strColumn.Append(props[i].Name);
                    strColumn.Append(",");
                }
                strColumn.Remove(strColumn.Length - 1, 1);
                sw.WriteLine(strColumn);    

//写入头部结束

//写入数据开始

                for (int i = 0; i < List.Count; i++)
                {
                    strValue.Remove(0, strValue.Length); //clear the temp row value写入值

                    strValue.Append(List[i].RoleName);//RoleName为list集合的字段名
                    strValue.Append(",");
                    strValue.Append(List[i].IsActive);//IsActive为list集合的字段名
                    sw.WriteLine(strValue); //按行写入数据
                }

//写入数据结束
            }
            catch (Exception)
            {
                successFlag = false;
            }
            finally
            {
                if (sw != null)
                {
                    sw.Dispose();
                }
                if (fs != null)
                {

                    fs.Close();
                }
            }

            return successFlag;
        }

调用

List<RoleBF> role = new List<RoleBF>();

 CreatExcelOrCSV cSV = new CreatExcelOrCSV();//方法所在的类
 bool flag = cSV.SaveDataToCSVFileRole(role, path1);

C#导出数据到 Excel文件:    

方法1  

  /// <summary>
        /// 数据流形式导出到excel 可用
        /// </summary>
        /// <param name="list"></param>
        /// <param name="filePath"></param>
        public static void DataExport(List<UserBF> list, string filePath)
        {
            if (list.Count > 0)
            {
                //用于创建文件
                using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
                {
                    //用于写入内容
                    using (StreamWriter streamWriter = new StreamWriter(new BufferedStream(fileStream), Encoding.Default))

                    {

                        //表头
                        string tbhead = "";
                        var entity = list[0].GetType();
                        PropertyInfo[] piList = entity.GetProperties();
                        foreach (PropertyInfo pi in piList)

                        {

                            tbhead += pi.Name + "\t";

                        }
                        //取完表头,换行
                        tbhead = tbhead.Substring(0, tbhead.Length - 1) + "\n";
                        //表头写入
                        streamWriter.Write(tbhead);
                        foreach (var v in list)
                        {

                            string tbbody = "导入数据";

                            StringBuilder tbBody = new StringBuilder();

                            for (int i = 0; i < piList.Length; i++)
                            {
                                object value = piList[i].GetMethod.Invoke(v, null);
                                tbBody.Append(value);//内容
                                tbBody.Append("\t");//自动跳到下一单元格
                            }

                            tbbody = tbBody.ToString();

                            tbbody = tbbody.Substring(0, tbbody.Length - 1) + "\n";//取完一行内容,换行

                            streamWriter.Write(tbbody);//内容写入

                        }

                    }
                }

                //需要添加 Microsoft.Office.Interop.Excel引用 
                Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
                if (app == null)//服务器上缺少Excel组件,需要安装Office软件
                {
                    return;
                }
                app.Visible = false;
                app.UserControl = true;
                string strTempPath = filePath;//模版excel

                app.Columns.AutoFit(); //自动调整列宽
            }

            else
            {

            }

        }

 方法2      

 /// <summary>
        /// 用Microsoft.Office.Interop.Excel生成Excel文件
        /// </summary>
        /// <param name="data">数据集合</param>
        /// <param name="FilePath">文件路径</param>
        public void CreateExcel(List<UserBF> data, string FilePath)
        {
            System.Reflection.Missing misValue = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            //设置禁止弹出保存和覆盖的询问提示框  
            xlApp.DisplayAlerts = false;
            xlApp.AlertBeforeOverwriting = false;
            //让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写  
            xlApp.Visible = false;
            //新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错  
            Workbooks workbooks = xlApp.Workbooks;
            Workbook workbook = workbooks.Add(true);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];

            //用反射获取类型的所有属性(以便后续生成所有Column的标题)
            Type type = typeof(UserBF);
            object obj = Activator.CreateInstance(type);
            PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            try
            {
                for (int i = 0; i < props.Length; i++)
                {
                    worksheet.Cells[1, i + 1] = props[i].Name; //write the column name
                }
                for (int i = 0; i < data.Count; i++)
                {
                    worksheet.Cells[i + 2, 1] = data[i].Name;//字段名
                    worksheet.Cells[i + 2, 2] = data[i].Account;//字段名
                    worksheet.Cells[i + 2, 3] = data[i].PassWord;//字段名
                    worksheet.Cells[i + 2, 4] = data[i].Phone;//字段名
                    worksheet.Cells[i + 2, 5] = data[i].Sex;//字段名
                    worksheet.Cells[i + 2, 6] = data[i].Age;//字段名
                    worksheet.Cells[i + 2, 7] = data[i].LastLoginAddress;//字段名
                    worksheet.Cells[i + 2, 8] = data[i].IsActive;//字段名
                }
                workbook.SaveAs(FilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                workbook.Close(Type.Missing, Type.Missing, Type.Missing);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                //确保Excel进程关闭  
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                workbook = null;
                xlApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
                xlApp = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曾弟弟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值