如何从datagridview获取excel列名

时间:2015-08-07 11:37:58

标签: c# excel winforms vba datagridview

大家好我有一个表单应用程序,用于重命名从excel获取数据的文件,我想用datagridview获取excel列名,我该怎么办?

编辑:评论上的excel图像

path = dataGridView1.Rows[i].Cells["K1"].Value.ToString();
            path2 = dataGridView1.Rows[i].Cells["K2"].Value.ToString();

那些K1和K2是其中一个excel列名的名称,但我想让它在所有excel列上工作如何完成?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;

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

        private void button1_Click(object sender, EventArgs e)
        {


            OleDbConnection baglan = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\STAJ\\AppData\\Roaming\\Skype\\My Skype Received Files\\ETKB-Aktarim-Test(1).xlsx ; Extended Properties='Excel 12.0 xml;HDR=YES;'");
            baglan.Open();
            string sorgu = "select * from [Sheet1$] ";
            OleDbDataAdapter data_adaptor = new OleDbDataAdapter(sorgu, baglan);
            baglan.Close();
            DataTable dt = new DataTable();
            data_adaptor.Fill(dt);
            dataGridView1.DataSource = dt;


            string path="";
            string path2 = "";
            string newFileName = "";
            string oldFileName = "";
            int i = 0;


            foreach (DataGridViewRow row in dataGridView1.Rows)
            {


                try
                {
                    path = dataGridView1.Rows[i].Cells["K1"].Value.ToString();
                    path2 = dataGridView1.Rows[i].Cells["K2"].Value.ToString();
                    oldFileName = path ;
                    newFileName = path2;
                    if (File.Exists(oldFileName))
                    {
                        File.Move(oldFileName, newFileName);
                    }  
                  i++;
                }
                catch (Exception ex)
    {
        MessageBox.Show("DOSYA ADI DEGISTIRILDI");
    }
            }

        }
    }
}

0 个答案:

没有答案