C# 把txt文件内容写入dataGridView控件

//编程环境:win7+vs2010  
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //建立一个打开文件的对话框
            using (OpenFileDialog dlgText = new OpenFileDialog())
            {
                dlgText.Filter = "文本文件|*.txt";
                if (dlgText.ShowDialog() == DialogResult.OK)
                {
                    //新建一个datatable用于保存读入的数据
                    DataTable dt = new DataTable();
                    //给datatable添加6个列标题
                    dt.Columns.Add("日期", typeof(String));
                    dt.Columns.Add("开盘价", typeof(String));
                    dt.Columns.Add("最高价", typeof(String));
                    dt.Columns.Add("最低价", typeof(String));
                    dt.Columns.Add("收盘价", typeof(String));
                    dt.Columns.Add("成交量", typeof(String));
                    //读入文件
                    using (StreamReader reader = new StreamReader(dlgText.FileName, Encoding.Default))
                    {
                        //循环读取所有行
                        while (!reader.EndOfStream)
                        {
                            //将每行数据,用“Tab”分割成6段
                            char[] separator = {'\t'};
                            string[] data = reader.ReadLine().Split(separator);
                            //string[] data = reader.ReadLine().Replace("----", "-").Split('-');
                            //新建一行,并将读出的数据分段,分别存入6个对应的列中
                            DataRow dr = dt.NewRow();
                            dr[0] = data[0];
                            dr[1] = data[1];
                            dr[2] = data[2];
                            dr[3] = data[3];
                            dr[4] = data[4];
                            dr[5] = data[5];
                            //将这行数据加入到datatable中
                            dt.Rows.Add(dr);
                        }
                    }
                    //将datatable绑定到datagridview上显示结果
                    this.dataGridView1.DataSource = dt;
                    //删除第一行
                    this.dataGridView1.Rows.RemoveAt(0);
                    //行头隐藏
                    this.dataGridView1.RowHeadersVisible = false;
                }
            }
        }
    }
}

你可以使用 C#DataGridView 控件与 OpenFileDialog 组件来读取和写入 Excel 文件。 首先,你需要引入以下命名空间: ```csharp using System; using System.Data; using System.Windows.Forms; using System.IO; using Excel = Microsoft.Office.Interop.Excel; ``` 然后,你可以创建一个方法来加载 Excel 文件DataGridView 中: ```csharp private void LoadExcelToDataGridView() { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm"; if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook = excelApp.Workbooks.Open(filePath); Excel.Worksheet worksheet = workbook.ActiveSheet; DataTable dt = new DataTable(); for (int i = 1; i <= worksheet.UsedRange.Columns.Count; i++) { dt.Columns.Add("Column " + i.ToString()); } for (int row = 1; row <= worksheet.UsedRange.Rows.Count; row++) { DataRow dr = dt.NewRow(); for (int col = 1; col <= worksheet.UsedRange.Columns.Count; col++) { dr[col - 1] = worksheet.Cells[row, col].Value; } dt.Rows.Add(dr); } dataGridView.DataSource = dt; workbook.Close(); excelApp.Quit(); } } ``` 上述代码中,我们使用了 Microsoft.Office.Interop.Excel 库来读取 Excel 文件并将其数据加载到 DataTable 中。然后,我们将 DataTable 设置为 DataGridView 的数据源。 接下来,你可以创建一个方法来将 DataGridView 的数据写入到 Excel 文件中: ```csharp private void SaveDataGridViewToExcel() { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { string filePath = saveFileDialog.FileName; Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook = excelApp.Workbooks.Add(); Excel.Worksheet worksheet = workbook.ActiveSheet; for (int col = 1; col <= dataGridView.Columns.Count; col++) { worksheet.Cells[1, col] = dataGridView.Columns[col - 1].HeaderText; } for (int row = 1; row <= dataGridView.Rows.Count; row++) { for (int col = 1; col <= dataGridView.Columns.Count; col++) { worksheet.Cells[row + 1, col] = dataGridView.Rows[row - 1].Cells[col - 1].Value; } } workbook.SaveAs(filePath); workbook.Close(); excelApp.Quit(); } } ``` 在上述代码中,我们使用了 Microsoft.Office.Interop.Excel 库来创建一个新的 Excel 文件,并将 DataGridView 的数据写入到该文件中。 最后,你可以在你的按钮点击事件中调用这两个方法: ```csharp private void btnLoad_Click(object sender, EventArgs e) { LoadExcelToDataGridView(); } private void btnSave_Click(object sender, EventArgs e) { SaveDataGridViewToExcel(); } ``` 请注意,为了使用 Microsoft.Office.Interop.Excel 库,你需要在项目中添加对 "Microsoft.Office.Interop.Excel" 的引用,并确保你的机器上已安装了 Microsoft Office。 希望这可以帮助到你!如果你有任何问题,请随时询问。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值