惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
博客园_首页
H
Help Net Security
WordPress大学
WordPress大学
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
罗磊的独立博客
博客园 - 三生石上(FineUI控件)
B
Blog
I
InfoQ
SecWiki News
SecWiki News
T
Tailwind CSS Blog
Spread Privacy
Spread Privacy
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Vulnerabilities – Threatpost
N
Netflix TechBlog - Medium
P
Palo Alto Networks Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Vercel News
Vercel News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
K
Kaspersky official blog
M
MIT News - Artificial intelligence
S
Schneier on Security
T
Threat Research - Cisco Blogs
F
Fortinet All Blogs
Cyberwarzone
Cyberwarzone
Scott Helme
Scott Helme
aimingoo的专栏
aimingoo的专栏
Martin Fowler
Martin Fowler
MyScale Blog
MyScale Blog
The Cloudflare Blog
Recent Announcements
Recent Announcements
Security Latest
Security Latest
G
GRAHAM CLULEY
IT之家
IT之家
Y
Y Combinator Blog
The Last Watchdog
The Last Watchdog
腾讯CDC
Google DeepMind News
Google DeepMind News
V
V2EX
S
Securelist
TaoSecurity Blog
TaoSecurity Blog
B
Blog RSS Feed
S
SegmentFault 最新的问题
博客园 - 叶小钗
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
Project Zero
Project Zero
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
F
Full Disclosure

博客园 - 尚書

类似于GROUP BY SUM() 用于字符串连接的语句 UBUNTU 14.04 INSTALL nsenter UBUNTU 14.04 DOCKER 1.4.1 Redis On Windows Run Redis On Windows C#.NET 加密解密:AES/DES/Base64/RSA/MD5/SHA256 Random Mongo的主从同步,以及备份与恢复 Mongodb 更多操作 Mongodb的备份/还原 mongodump/mongorestore itextsharp多语言(中日韩等)填表解决 [C#]HttpWebRequest、HttpWebRespoonse、WebRequest and WebResponse、WebClient差异 [筆記] string.Format 格式整理 微软放出五大语种Windows 8消费者预览版ISO镜像 [MVC] 获取请求时缺少"+"的处理办法 How to fix the bug that missing plus in Request.QueryString/Form [SQL SERVER] 数字补0 [SQL SERVER] 用SQL语句读取Execl数据 [SQL SERVER] 跨库查询--分布式查询 Install MongoDB as a windows service
CSharpJExcel Read/Write Excel
尚書 · 2011-11-24 · via 博客园 - 尚書

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using CSharpJExcel.Jxl;
using CSharpJExcel.Jxl.Write;
using CsvHelper.Configuration;

namespace Common.Extensions
{
    public static class ExcelExtension
    {
        public static IEnumerable<T> GetRecordsFromExcel<T>(this string path) where T : class, new()
        {
            var file = new FileInfo(path);

            Debug.Assert(!string.IsNullOrWhiteSpace(file.DirectoryName));

            Type type = typeof(T);
            var properties = type.GetProperties().Where(t => t.IsDefined(typeof(CsvFieldAttribute), true)).ToList();
            var headerNames = properties.Select(GetCsvFieldName).ToList();

            var workbook = Workbook.getWorkbook(file);
            Sheet sheet = workbook.getSheet(0);

            var headerCells = sheet.getRow(0);

            var query = from headerName in headerNames
                        join headerCell in headerCells
                            on headerName equals headerCell.getContents()
                        select new
                                   {
                                       Key = headerName,
                                       Value = headerCell.getColumn()
                                   };

            var nameIndexes = query.ToDictionary(t => t.Key, t => t.Value);
            var result = new List<T>();
            for (int row = 1; row < sheet.getRows(); row++)
            {
                var t = new T();

                foreach (var property in properties)
                {
                    string csvFiledName = property.GetCsvFieldName();
                    if (nameIndexes.ContainsKey(csvFiledName))
                    {
                        var column = nameIndexes[csvFiledName];
                        var value = sheet.getCell(column, row).getContents();
                        property.SetValue(t, value, null);
                    }
                }
                result.Add(t);
            }

            workbook.close();
            return result;
        }

        private static string GetCsvFieldName(this PropertyInfo property)
        {
            return ((CsvFieldAttribute)property.GetCustomAttributes(typeof(CsvFieldAttribute), true)[0]).Name;
        }

        public static void WriteRecordsToExcel<T>(this List<T> records, string path) where T : class
        {
            var file = new FileInfo(path);

            Debug.Assert(!string.IsNullOrWhiteSpace(file.DirectoryName));

            if (!Directory.Exists(file.DirectoryName))
                Directory.CreateDirectory(file.DirectoryName);

            var ws = new WorkbookSettings();
            ws.setEncoding("UTF8");
            WritableWorkbook workbook = Workbook.createWorkbook(file, ws);
            WritableSheet sheet = workbook.createSheet(file.Name, 0);

            Type type = typeof(T);

            var properties = type.GetProperties().Where(t => t.IsDefined(typeof(CsvFieldAttribute), true)).ToList();

            for (int j = 0; j < properties.Count(); j++)
            {
                var attribute = (CsvFieldAttribute)properties[j].GetCustomAttributes(typeof(CsvFieldAttribute), true)[0];
                var cell = new Label(j, 0, attribute.Name);
                sheet.addCell(cell);
            }

            for (int i = 0; i < records.Count(); i++)
            {
                for (int j = 0; j < properties.Count(); j++)
                {
                    object value = properties[j].GetValue(records[i], null);
                    string s = value == null ? "" : value.ToString();
                    var cell = new Label(j, i + 1, s);
                    sheet.addCell(cell);
                }
            }

            workbook.write();
            workbook.close();
        }
    }
}