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

C#多个CSV文件合并成一个文件

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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        string FileName = string.Empty;
        DataTable dtExcelData;
        public Form1()
        {
            InitializeComponent();
        }

        private void bthChose_Click(object sender, EventArgs e)
        {
            OpenFileDialog opd = new OpenFileDialog();//实例化选择打开窗口对象
            opd.Multiselect = false;//定义不允许多选
            opd.Filter = "(*.*)|*.csv";//设置可以选择所有文件
            if (opd.ShowDialog() == DialogResult.OK)
            {
                //写入自己的代码
                txtFileName.Text = opd.FileName;
                FileName = opd.FileName;

            }
            opd.Dispose();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string path = "";
            string fname = "";
            if (FileName.Length <= 0)
            {
                MessageBox.Show("请上传文件");
                return;
            }

            else if (System.IO.Path.GetExtension(FileName) != ".csv")
            {
                MessageBox.Show("请上传csv格式文件");
                return;
            }
            else
            {
                path = FileName.Substring(0, FileName.LastIndexOf("\\") + 1);
              //  fname = FileName.Substring(FileName.LastIndexOf("\\") + 1);    
            }
            GetDate(path);
        }


        public void GetDate(string path)
        {
            try
            {
                DataGridView dgv = new DataGridView();

                dgv.RowHeadersVisible = true;
                dgv.Columns.Clear();
                dgv.Columns.Add("Sort", "Sort");
                dgv.Columns.Add("TN", "TN");
                dgv.Columns.Add("FileName", "FileName");
                string[] FileNameList = Directory.GetFiles(path);
                Array.Sort(FileNameList,new TSort() );
              
             
                int i = 0;
                foreach (String filePath in FileNameList)
                {
                    i++;
                
                    string fname = filePath.Substring(FileName.LastIndexOf("\\") + 1);   
                    StreamReader sr = new StreamReader(filePath);
                    while (true)
                    {
                        String strData = sr.ReadLine();
                        if (!String.IsNullOrEmpty(strData))
                        {
                            String[] strValue = strData.Split(',');
                            int index = dgv.Rows.Add();
                            DataGridViewRow dr = dgv.Rows[index];
                            dr.Cells[0].Value = i.ToString();
                            dr.Cells[1].Value = strValue[0];
                            dr.Cells[2].Value = fname;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                if (dgv.Rows.Count > 0)
                {
                   

                    ExcelHelper eh = new ExcelHelper();
                    eh.OutToExcelFromDataGridView("TNT", dgv, false);

                }
            } catch (Exception ex)
            {
                MessageBox.Show("抱歉出错了!"+ex.Message);
            }

        }

    }
}

 

 

 

 

using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsFormsApplication1
{
    public class TSort : System.Collections.IComparer
    {
        public int Compare(object x, object y)
        {
            string s1 = (string)x;
            string s2 = (string)y;
            if (s1.Length > s2.Length) return 1;
            if (s1.Length < s2.Length) return -1;
            for (int i = 0; i < s1.Length; i++)
            {
                if (s1[i] > s2[i]) return 1;
                if (s1[i] < s2[i]) return -1;
            }
            return 0;
        }
    } 

}

 

 

 

 

 

 

 

using System;
using System.IO;
using System.Data;
using System.Collections;
using System.Data.OleDb;
using System.Web;
using System.Windows.Forms;
using System.Text;

using Microsoft.Office.Interop.Excel;


/// <summary>
/// Excel操作类
/// </summary>
/// Microsoft Excel 11.0 Object Library
public  class ExcelHelper
{


    public  bool OutToExcelFromDataGridView(string title, DataGridView dgv, bool isShowExcel)
    {
        int titleColumnSpan = 0;//标题的跨列数
        string fileName = "tnt";//保存的excel文件名
        int columnIndex = 1;//列索引
        if (dgv.Rows.Count == 0)
            return false;
        /*保存对话框*/
        //SaveFileDialog sfd = new SaveFileDialog();
        //sfd.Filter = "导出Excel(*.xls)|*.xls";
        //sfd.FileName = title + DateTime.Now.ToString("yyyyMMddhhmmss");

        //if (sfd.ShowDialog() == DialogResult.OK)
        //{
        //    fileName = sfd.FileName;
            /*建立Excel对象*/
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            if (excel == null)
            {
                MessageBox.Show("无法创建Excel对象,可能您的计算机未安装Excel!");
                return false;
            }
            try
            {
                excel.Application.Workbooks.Add(true);
                excel.Visible = isShowExcel;
                /*分析标题的跨列数*/
                foreach (DataGridViewColumn column in dgv.Columns)
                {
                    if (column.Visible == true)
                        titleColumnSpan++;
                }
                /*合并标题单元格*/
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet;
                //worksheet.get_Range("A1", "C10").Merge();           
                worksheet.get_Range(worksheet.Cells[1, 1] as Range, worksheet.Cells[1, titleColumnSpan] as Range).Merge();
                /*生成标题*/
                excel.Cells[1, 1] = title;
                (excel.Cells[1, 1] as Range).HorizontalAlignment = XlHAlign.xlHAlignCenter;//标题居中
                //生成字段名称
                columnIndex = 1;
                for (int i = 0; i < dgv.ColumnCount; i++)
                {
                    if (dgv.Columns[i].Visible == true)
                    {
                        excel.Cells[2, columnIndex] = dgv.Columns[i].HeaderText;
                        (excel.Cells[2, columnIndex] as Range).HorizontalAlignment = XlHAlign.xlHAlignCenter;//字段居中
                        columnIndex++;
                    }
                }
                //填充数据             
                for (int i = 0; i < dgv.RowCount; i++)
                {
                    columnIndex = 1;
                    for (int j = 0; j < dgv.ColumnCount; j++)
                    {
                        if (dgv.Columns[j].Visible == true)
                        {
                            if (dgv[j, i].ValueType == typeof(string))
                            {
                                excel.Cells[i + 3, columnIndex] = "'" + dgv[j, i].Value.ToString();
                            }
                            else
                            {
                                excel.Cells[i + 3, columnIndex] = dgv[j, i].Value.ToString();
                            }
                            (excel.Cells[i + 3, columnIndex] as Range).HorizontalAlignment = XlHAlign.xlHAlignLeft;//字段居中
                            columnIndex++;
                        }
                    }
                }
                worksheet.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            }
            catch { }
            finally
            {
                excel.Quit();
                excel = null;
                GC.Collect();
            }
            //KillProcess("Excel");
            return true;
        //}
        //else
        //{
        //    return false;
        //}
    }
    private static void KillProcess(string processName)//杀死与Excel相关的进程
    {
        System.Diagnostics.Process myproc = new System.Diagnostics.Process();//得到所有打开的进程
        try
        {
            foreach (System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcessesByName(processName))
            {
                if (!thisproc.CloseMainWindow())
                {
                    thisproc.Kill();
                }
            }
        }
        catch (Exception Exc)
        {
            throw new Exception("", Exc);
        }
    }

 

   

}


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C#Winform窗体传值利用委托子窗体传值给父窗体发布时间:2022-07-14
下一篇:
c#唯一id发布时间:2022-07-14
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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