zoukankan      html  css  js  c++  java
  • c# 数据对象导出成excel或csv文件

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using Excel = Microsoft.Office.Interop.Excel;
    namespace  Helper
    {
        public class EXCEL_ExportHelper
        {
            class EXCEL_EXPORT
            {
                public bool Export<T>(List<T> source, string saveFileName, out string errMsg)
                {
                    errMsg = "";
                    Excel.Application xlApp = new Excel.Application();
                    if (xlApp == null)
                    {
                        errMsg = "无法创建Excel对象,可能您的机子未安装Excel";
                        return false;
                    }
                    Excel.Workbook workbook = xlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
                    object missing = System.Reflection.Missing.Value;
                    try
                    {
                        //写入字段
                        Type t = typeof(T);
                        PropertyInfo[] infos = t.GetProperties();
                        for (int i = 0; i < infos.Length; i++)
                        {
                            object[] customerAttr = infos[i].GetCustomAttributes(typeof(ChineseName), false);
                            if (customerAttr != null && customerAttr.Length > 0 && customerAttr[0] is ChineseName)
                            {
                                ChineseName cName = customerAttr[0] as ChineseName;
                                workbook.Worksheets[1].Cells[1, i + 1] = cName.Name;
                            }
                            else
                            {
                                workbook.Worksheets[1].Cells[1, i + 1] = infos[i].Name;
                            }
                            ((Excel.Range)workbook.Worksheets[1].Cells[1, i + 1]).Font.Bold = true;
                        }
                        //写入数值
                        for (int row = 0; row < source.Count; row++)//一条数据代表一行
                        {
                            for (int colome = 0; colome < infos.Length; colome++)//一条数据代表一列
                            {
                                workbook.Worksheets[1].Cells[row + 2, colome + 1] = "'" + infos[colome].GetValue(source[row], null).ToString();
                            }
                        }
                        workbook.Worksheets[1].Columns.AutoFit();
                        workbook.SaveAs(saveFileName);
                    }
                    catch (Exception ex)
                    {
                        errMsg = ex.Message;
                        return false;
                    }
                    finally
                    {
                        workbook.Close(false);
                        workbook = null;
                        xlApp.Quit();
                        xlApp = null;
                    }
                    return true;
                }
            }
    
            class CSV_EXPORT
            {
                public bool Export<T>(List<T> source, string savePath, out string errMsg)
                {
                    errMsg = "";
                    int fileIndex = 1;
                    string saveFileName = savePath;
                    while (File.Exists(saveFileName))
                    {
                        saveFileName = savePath.Substring(0, savePath.LastIndexOf('.') - 1) + "_" + fileIndex + savePath.Substring(savePath.LastIndexOf('.'), savePath.Length - savePath.LastIndexOf('.'));
                        fileIndex++;
                    }
                    FileStream fs = new FileStream(saveFileName, FileMode.OpenOrCreate);
                    StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                    try
                    {
                        //写入字段
                        Type t = typeof(T);
                        PropertyInfo[] infos = t.GetProperties();
                        string firstline = "";
                        for (int i = 0; i < infos.Length; i++)
                        {
                            object[] customerAttr = infos[i].GetCustomAttributes(typeof(ChineseName), false);
                            if (customerAttr != null && customerAttr.Length > 0 && customerAttr[0] is ChineseName)
                            {
                                ChineseName cName = customerAttr[0] as ChineseName;
                                firstline = firstline + cName.Name + ",";
                            }
                            else
                            {
                                firstline = firstline + infos[i].Name;
                            }
    
                        }
                        //写入数值
                        for (int row = 0; row < source.Count; row++)//一条数据代表一行
                        {
                            string rowline = "";
                            for (int colome = 0; colome < infos.Length; colome++)//一条数据代表一列
                            {
                                rowline = rowline + infos[colome].GetValue(source[row], null).ToString() + ",'";
                            }
                            firstline = firstline + "
    " + rowline;
                        }
                        sw.Write(firstline);
    
                    }
                    catch (Exception ex)
                    {
                        errMsg = ex.Message;
                        return false;
                    }
                    finally
                    {
                        sw.Close();
                        sw.Dispose();
                        fs.Close();
                        fs.Dispose();
                    }
                    return true;
                }
            }
    
            /// <summary>
            /// 导出数据到文件,可以是excel或csv文件
            /// </summary>
            /// <typeparam name="T">数据类型(请将类型字段加扩展属性ChineseName,这样导出的文件里就以中文名为字段了。如果没有加扩展属性,则只能以英文来显示)</typeparam>
            /// <param name="source">数据源</param>
            /// <param name="saveFileName">要保存的路径</param>
            /// <param name="errMsg">错误反馈</param>
            /// <returns>导出结果</returns>
            public static bool Export<T>(List<T> source, string saveFileName, out string errMsg)
            {
                string extention = saveFileName.Substring(saveFileName.LastIndexOf('.'), saveFileName.Length - saveFileName.LastIndexOf('.'));
                if (extention == ".csv")
                {
                    CSV_EXPORT TEMP_CLASS = new CSV_EXPORT();
                    bool OK = TEMP_CLASS.Export<T>(source, saveFileName, out errMsg);
                    return OK;
                }
                else if (extention == ".xlsx")
                {
                    EXCEL_EXPORT TEMP_CLASS = new EXCEL_EXPORT();
                    bool OK = TEMP_CLASS.Export<T>(source, saveFileName, out errMsg);
                    TEMP_CLASS = null;
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    return OK;
                }
                else
                {
                    errMsg = "不支持的格式类型,请重试或检查";
                    return false;
                }
            }
        }
    }
  • 相关阅读:
    夯实JavaScript基础之prototype, __proto__, instanceof
    入住博客园
    基础知识盲点——2
    Vuecli开发笔记三引入外部插件
    转让阿里云服务器(CPU2G+内存2G+带宽5M+硬盘150G)
    ubuntu 1
    ftp命令
    mysql数据库备份及恢复命令mysqldump,source的用法
    wordpress option的操作
    wordpress作者角色添加不了视频代码
  • 原文地址:https://www.cnblogs.com/congqiandehoulai/p/12727884.html
Copyright © 2011-2022 走看看