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;
                }
            }
        }
    }
  • 相关阅读:
    js外观模式
    微服务架构的基础框架选择:Spring Cloud还是Dubbo?
    JAVA 中BIO,NIO,AIO的理解
    Reactor和Proactor模式的讲解(关于异步,同步,阻塞与非阻塞)
    JVM(Java虚拟机)优化大全和案例实战
    php编译安装后,加扩展模块
    mysql查所有列名
    cannot get uid for user 'www'
    rabbitmq management Login Failed
    nginx 安装过程中的not found
  • 原文地址:https://www.cnblogs.com/congqiandehoulai/p/12727884.html
Copyright © 2011-2022 走看看