C# 从数据库读取数据, 导出到CSV

using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSVtoDataBase
{
    public class SqlSugarHelper
    {
        public static string ConnectionString = string.Empty; //必填, 数据库连接字符串
        public static SqlSugarClient db
        {
            get => new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = ConnectionString,
                DbType = DbType.Sqlite,         //必填, 数据库类型
                IsAutoCloseConnection = true,       //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
                //InitKeyType = InitKeyType.Attribute    //默认SystemTable, codefist需要使用Attribute
                InitKeyType = InitKeyType.SystemTable
            });
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSVtoDataBase
{
    public class SqlSugarService
    {
        /// <summary>
        /// 设置连接字符串
        /// </summary>
        /// <param name="ConnectionStr"></param>
        public static void SetConnectionStr(string ConnectionStr)
        {
            SqlSugarHelper.ConnectionString = ConnectionStr;
        }
    }
}

using Entitys;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSVtoDataBase
{
    public interface IResponsitory
    {
        List<ActualData> GetActualDatas();

        DataTable GetDataTableActualDatas();
        int InsertActualData(List<ActualData> actualDatas);

        DataTable GetDataTableSysAdmin();
        int InsertSysAdmin(List<Sysadmins> sysadmins);

    }
}

using Entitys;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSVtoDataBase
{
    public class SugarResponsitory: IResponsitory
    {
        private SqlSugarClient _db = SqlSugarHelper.db;
        public SqlSugarClient Db { get => _db; set => _db = value; }

        public List<ActualData> GetActualDatas()
        {
            return _db.Queryable<ActualData>().OrderBy(x => x.Id,OrderByType.Desc).Take(50).ToList();
        }

        public DataTable GetDataTableActualDatas()
        {
            return _db.Queryable<ActualData>()
                .OrderBy(x => x.Id, OrderByType.Desc)
                .Take(50)
                .Select(x => new 
                { 
                    InsertTime = x.InsertTime,
                    VarName = x.VarName,
                    Remark = x.Remark
                }).ToDataTable();
        }

        public int InsertActualData(List<ActualData> actualDatas)
        {
            int count = _db.Insertable(actualDatas).ExecuteCommand();
            return count;
        }

        public DataTable GetDataTableSysAdmin()
        {
            return _db.Queryable<Sysadmins>()
                .Select(x => new
                {
                    UserManage = x.UserManage,
                    LoginName = x.LoginName,
                    Report = x.Report,
                    LoginPwd = x.LoginPwd,
                    SysLog = x.SysLog,
                    SysSet = x.SysSet,
                    Trend = x.Trend,
                    HandCtrl = x.HandCtrl,
                    AutoCtrl = x.AutoCtrl,
                }).ToDataTable();
        }

        public int InsertSysAdmin(List<Sysadmins> sysadmins)
        {
            return _db.Insertable(sysadmins).ExecuteCommand();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSVtoDataBase
{
    public class CSVHelper
    {
        /// <summary>
        /// 写入CSV
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="dt">要写入的datatable</param>
        public void WriteCSV(string fileName, DataTable dt)
        {
            FileStream fs;
            StreamWriter sw;
            string data = null;

            //判断文件是否存在,存在就不再次写入列名
            if (!File.Exists(fileName))
            {
                fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                sw = new StreamWriter(fs, Encoding.UTF8);

                //写出列名称
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    data += dt.Columns[i].ColumnName.ToString();
                    if (i < dt.Columns.Count - 1)
                    {
                        data += ",";//中间用,隔开
                    }
                }
                sw.WriteLine(data);
            }
            else
            {
                fs = new FileStream(fileName, FileMode.Append, FileAccess.Write);
                sw = new StreamWriter(fs, Encoding.UTF8);
            }

            //写出各行数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                data = null;
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    data += dt.Rows[i][j].ToString();
                    if (j < dt.Columns.Count - 1)
                    {
                        data += ",";//中间用,隔开
                    }
                }
                sw.WriteLine(data);
            }
            sw.Close();
            fs.Close();
        }



        /// <summary>
        /// 读取CSV文件
        /// </summary>
        /// <param name="fileName">文件路径</param>
        public DataTable ReadCSV(string fileName)
        {
            DataTable dt = new DataTable();
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.UTF8);

            //记录每次读取的一行记录
            string strLine = null;
            //记录每行记录中的各字段内容
            string[] arrayLine = null;
            //分隔符
            string[] separators = { "," };
            //判断,若是第一次,建立表头
            bool isFirst = true;

            //列的个数
            int dtColumns = 0;

            //逐行读取CSV文件
            while ((strLine = sr.ReadLine()) != null)
            {
                strLine = strLine.Trim();//去除头尾空格
                arrayLine = strLine.Split(separators, StringSplitOptions.RemoveEmptyEntries);//分隔字符串,返回数组

                if (isFirst)  //建立表头
                {
                    dtColumns = arrayLine.Length;//列的个数
                    for (int i = 0; i < dtColumns; i++)
                    {
                        dt.Columns.Add(arrayLine[i]);//每一列名称
                    }
                    isFirst = false;
                }
                else   //表内容
                {
                    DataRow dataRow = dt.NewRow();//新建一行
                    for (int j = 0; j < dtColumns; j++)
                    {
                        dataRow[j] = arrayLine[j];
                    }
                    dt.Rows.Add(dataRow);//添加一行
                }
            }
            sr.Close();
            fs.Close();

            return dt;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CSVtoDataBase
{
    public class ModelHelper<T> where T : new()  // 此处一定要加上new()
    {

        public  IList<T> DataTableToModel(DataTable dt)
        {

            IList<T> list = new List<T>();// 定义集合
            Type type = typeof(T); // 获得此模型的类型
            string tempName = "";
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
                foreach (PropertyInfo pro in propertys)
                {
                    tempName = pro.Name;
                    if (dt.Columns.Contains(tempName))
                    {
                        if (!pro.CanWrite) continue;
                        object value = dr[tempName];
                        if (value != DBNull.Value)
                            pro.SetValue(t, value, null);
                    }
                }
                list.Add(t);
            }
            return list;
        }
    }
}

using Entitys;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSVtoDataBase
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string path = Directory.GetCurrentDirectory();
            string str1 = @"\DataBase\sb1.csv";
            string str2 = @"\DataBase\Monitor.db";
            
            SqlSugarService.SetConnectionStr("Data Source=" + path + str2);

            SugarResponsitory sugar = new SugarResponsitory();
            CSVHelper cSVHelper = new CSVHelper();
            TabletoList tabletoList = new TabletoList();
            ModelHelper<Sysadmins> modelHelper = new ModelHelper<Sysadmins>();

            DataTable sys = sugar.GetDataTableSysAdmin();
            
            //写入csv
            cSVHelper.WriteCSV(path+str1, sys);

            DataTable sys1 = cSVHelper.ReadCSV(path + str1);

            //List<Sysadmins> writeSys = tabletoList.TableToListModel<Sysadmins>(sys1);
            //List<Sysadmins> writeSys = tabletoList.DataTableToList<Sysadmins>(sys1);
            //sugar.InsertSysAdmin(writeSys);

            //List<ActualData> act2 = tabletoList.TableToListModel<ActualData>(act);
            //foreach (ActualData temp in act2)
            //{
            //    Console.WriteLine($"{temp.VarName}+{temp.Id}");

            //}

            Console.ReadKey();
        }
    }
}

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C# 中,你可以使用 ADO.NET 来连接和操作数据库。要将数据库中的数据一键导出,你可以执行以下步骤: 1. 首先,确保你已经添加了对 System.Data 命名空间的引用。 2. 创建一个连接字符串,用于连接到数据库。连接字符串包含数据库的相关信息,如服务器名称、数据库名称、身份验证方式等。下面是一个连接到 SQL Server 数据库的示例连接字符串: ```csharp string connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"; ``` 3. 创建一个 SqlConnection 对象,并使用连接字符串初始化它: ```csharp using (SqlConnection connection = new SqlConnection(connectionString)) { // 与数据库建立连接 connection.Open(); // 创建一个 SqlCommand 对象,用于执行 SQL 查询 SqlCommand command = new SqlCommand("SELECT * FROM TableName", connection); // 创建一个 SqlDataReader 对象,用于读取查询结果 SqlDataReader reader = command.ExecuteReader(); // 创建一个 StringBuilder 对象,用于保存导出的数据 StringBuilder data = new StringBuilder(); // 遍历查询结果,将数据添加到 StringBuilder 对象中 while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { data.Append(reader[i].ToString()); data.Append(","); } data.AppendLine(); } // 关闭 SqlDataReader 对象 reader.Close(); // 关闭数据库连接 connection.Close(); // 将导出的数据保存到文件 File.WriteAllText("exported_data.csv", data.ToString()); } ``` 上述代码将从名为 "TableName

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

潘诺西亚的火山

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

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

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

打赏作者

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

抵扣说明:

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

余额充值