Fork me on GitHub

使用OleDB保存数据到Excel

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
复制代码

类内容:

 

复制代码
代码
namespace Jd.RestoreNotify.Data
{
    
public static class ExcelHelper
    {
        
/// <summary>
        
/// 
        
/// </summary>
        
/// <typeparam name="T">Model类型</typeparam>
        
/// <param name="list">列表</param>
        
/// <param name="tmppath">模板文件(空的excel文件)地址</param>
        
/// <param name="outputpath">要输出的地址</param>
        
/// <param name="sheetname">excel的sheet名称</param>
        
/// <param name="propdict">要导出的列名列表</param>
        
/// <returns></returns>
        public static bool ExportToExcel<T>(IList<T> list, string tmppath, string outputpath, string sheetname, NameValueCollection propdict)
            
where T : class
        {
            
if (list == null || list.Count == 0)
            {
                
throw new ArgumentNullException("该列表没有实际的值""list");
            }

            
#region 判断模板文件、保存路径
            
if (!File.Exists(tmppath))
            {
                
throw new FileNotFoundException("模板文件路径不正确,找不到模板文件");
            }
            
if (File.Exists(outputpath))
            {
                File.Delete(outputpath);
            }
            File.Copy(tmppath, outputpath);
            
#endregion
            sheetname 
= string.IsNullOrEmpty(sheetname) ? "Sheet1" : sheetname;
            
string excelconntext = "Provider=Microsoft.Jet.OleDB.4.0;Data Source=" + outputpath + ";Extended Properties = \"Excel 8.0;HDR=Yes;\"";

            
using (OleDbConnection cn = new OleDbConnection(excelconntext))
            {
                cn.Open();
                OleDbCommand com 
= cn.CreateCommand();
                PropertyInfo[] ps 
= typeof(T).GetProperties();
                List
<PropertyInfo> proplist = new List<PropertyInfo>();
                StringBuilder sb 
= new StringBuilder();
                sb.Append(
"Create Table [" + sheetname + "$](");

                StringBuilder sb2 
= new StringBuilder();
                sb2.Append(
"Insert into [" + sheetname + "$] values(");
                
foreach (var item in ps)
                {
                    
string head = propdict[item.Name];
                    
if (string.IsNullOrEmpty(head)) continue;
                    
else proplist.Add(item);
                    sb.Append(head 
+ " ");
                    
switch (item.PropertyType.Name)
                    {
                        
case "String": sb.Append("Char,"); break;
                        
case "Decimal": sb.Append("Decimal,"); break;
                        
case "DateTime": sb.Append("Char,"); break;
                        
case "Int32": sb.Append("Integer,"); break;
                        
default: sb.Append("Char,");
                            
break;
                    }
                    sb2.Append(
"@" + item.Name + " ,");
                }
                com.CommandText 
= sb.ToString().Trim(','+ ")";
                com.ExecuteNonQuery();
//创建表头

                com.CommandText 
= sb2.ToString().Trim(','+ ")";

                
foreach (var item in list)
                {
                    OleDbParameter[] pars 
= new OleDbParameter[proplist.Count];
                    
for (int i = 0; i < proplist.Count; i++)
                    {
                        pars[i] 
= new OleDbParameter(proplist[i].Name, proplist[i].GetValue(item, null?? "");
                    }
                    com.Parameters.Clear();
                    com.Parameters.AddRange(pars);
                    com.ExecuteNonQuery();
//写入每行的数据
                }
            }

            
return true;
        }
    }
}
复制代码

 

 

posted @   TimGong  阅读(505)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示