• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

c#将DataTable内容导出为CSV文件

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

写了个类:

 class DataTableAndCSV
    {
        public static DataTable csvToDataTable(string file)
        {
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;'"; // Excel file  
            if (file.EndsWith(".csv"))
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='TEXT;HDR=Yes;FMT=Delimited;'"; // csv file:HDR=Yes-- first line is header  
            //strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='TEXT;HDR=Yes;FMT=Delimited;'"; // csv file:HDR=Yes-- first line is header  
            OleDbConnection oleConn = new OleDbConnection(strConn);
            oleConn.Open();
            DataTable sheets = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (sheets == null || sheets.Rows.Count < 1)
            {
                return null;
            }
            String fileName = sheets.Rows[0]["TABLE_NAME"].ToString(); // sheets.Rows[0] -- first sheet of excel  
            if (file.EndsWith(".csv"))
                fileName = file.Substring(file.LastIndexOf("/"));
            string olestr = "select * from [" + fileName + "]";
            if (file.EndsWith(".csv"))
                olestr = "select * from [" + fileName + "]";
            OleDbCommand oleComm = new OleDbCommand(olestr, oleConn);
            oleComm.Connection = oleConn;
            OleDbDataAdapter oleDa = new OleDbDataAdapter();
            oleDa.SelectCommand = oleComm;
            DataSet ds = new DataSet();
            oleDa.Fill(ds);
            oleConn.Close();
            return ds.Tables[0];
        }

        public static void dataTableToCsv(DataTable table, string file)
        {
            FileInfo fi = new FileInfo(file);
            string path = fi.DirectoryName;
            string name = fi.Name;
            //\/:*?"<>|
            //把文件名和路径分别取出来处理
            name = name.Replace(@"\", "");
            name = name.Replace(@"/", "");
            name = name.Replace(@":", "");
            name = name.Replace(@"*", "");
            name = name.Replace(@"?", "");
            name = name.Replace(@"<", "");
            name = name.Replace(@">", "");
            name = name.Replace(@"|", "");
            string title = "";

            FileStream fs = new FileStream(path + "\\" + name, FileMode.Create);
            StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);

            for (int i = 0; i < table.Columns.Count; i++)
            {
                title += table.Columns[i].ColumnName + ",";
            }
            title = title.Substring(0, title.Length - 1) + "\n";
            sw.Write(title);

            foreach (DataRow row in table.Rows)
            {
                if (row.RowState == DataRowState.Deleted) continue;
                string line = "";
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    line += row[i].ToString().Replace(",", "") + ",";
                }
                line = line.Substring(0, line.Length - 1) + "\n";

                sw.Write(line);
            }

            sw.Close();
            fs.Close();
        }

        public static void dataTableToCsv(DataTable table, string file, string Title)
        {
            FileInfo fi = new FileInfo(file);
            string path = fi.DirectoryName;
            string name = fi.Name;
            //\/:*?"<>|
            //把文件名和路径分别取出来处理
            name = name.Replace(@"\", "");
            name = name.Replace(@"/", "");
            name = name.Replace(@":", "");
            name = name.Replace(@"*", "");
            name = name.Replace(@"?", "");
            name = name.Replace(@"<", "");
            name = name.Replace(@">", "");
            name = name.Replace(@"|", "");
            string title = "";

            FileStream fs = new FileStream(path + "\\" + name, FileMode.Create);
            StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);

            title += Title + ",";
            for (int i = 1; i < table.Columns.Count; i++)
            {
                title += ",";
            }
            title = title.Substring(0, title.Length - 1) + "\n";
            sw.Write(title);
            title = "";

            for (int i = 0; i < table.Columns.Count; i++)
            {
                title += table.Columns[i].ColumnName + ",";
            }
            title = title.Substring(0, title.Length - 1) + "\n";
            sw.Write(title);

            foreach (DataRow row in table.Rows)
            {
                if (row.RowState == DataRowState.Deleted) continue;
                string line = "";
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    line += row[i].ToString().Replace(",", "") + ",";
                }
                line = line.Substring(0, line.Length - 1) + "\n";

                sw.Write(line);
            }

            sw.Close();
            fs.Close();
        }

        //public static void ExportToSvc(DataTable dt, string strFileName)
        //{
        //    string strPath = strFileName;
        //    if (File.Exists(strPath))
        //    {
        //        File.Delete(strPath);
        //    }
        //    //先打印标头
        //    StringBuilder strColu = new StringBuilder();
        //    StringBuilder strValue = new StringBuilder();
        //    int i = 0;
        //    try
        //    {
        //        StreamWriter sw = new StreamWriter(new FileStream(strPath, FileMode.CreateNew), Encoding.GetEncoding("GB2312"));
        //        for (i = 0; i <= dt.Columns.Count - 1; i++)
        //        {
        //            strColu.Append(dt.Columns[i].ColumnName);
        //            strColu.Append(",");
        //        }
        //        strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符
        //        sw.WriteLine(strColu);
        //        foreach (DataRow dr in dt.Rows)
        //        {
        //            strValue.Remove(0, strValue.Length);//移出
        //            for (i = 0; i <= dt.Columns.Count - 1; i++)
        //            {
        //                strValue.Append(dr[i].ToString());
        //                strValue.Append(",");
        //            }
        //            strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
        //            sw.WriteLine(strValue);
        //        }
        //        sw.Close();
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //    ////System.Diagnostics.Process.Start(strPath);
        //}
    }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
windbg的时间旅行实现对C#程序的终极调试发布时间:2022-07-10
下一篇:
C#对象的拷贝发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap