如何从excel复制数据并粘贴到lisview中 [英] how to copy data from excel and paste into lisview

查看:131
本文介绍了如何从excel复制数据并粘贴到lisview中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨所有





i希望从excel复制数据并粘贴到lisview(windows应用程序)。如何做到这一点。请有人告诉我..





感谢你。

hi to all


i want to copy data from excel and paste into lisview(windows application) .how to do it.can anyone tell me please..


thanking you.

推荐答案

首先,连接到Excel,并将电子表格读入DateTable

非常简单:

First, connect to Excel, and read the spreadsheet into a DateTable
Pretty simple:
private static DataTable GenerateExcelData(string path)
    {
    OleDbConnection con;
    if (Path.GetExtension(path) == ".xls")
        {
        con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
        }
    else if (Path.GetExtension(path) == ".xlsx")
        {
        con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
        }
    else
        {
        throw new ApplicationException("Unknown date file type");
        }
    con.Open();
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1


,con); ;
OleDbDataAdapter da = new OleDbDataAdapter( SELECT * FROM [Sheet1
", con); ; OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1


,con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
con.Dispose();
return dt;
}
", con); DataTable dt = new DataTable(); da.Fill(dt); con.Close(); con.Dispose(); return dt; }



将它变成列表视图更难(但DataGridView很简单!只需将DataSource设置为数据表即可为你做这个。)

但是,这会做你想要的事情:


Getting that into a listview is harder (but a DataGridView is easy! Just set the DataSource to teh data table and it'll do it for you).
But, this will do something like what you want:

foreach (DataRow row in dt.Rows)
    {
    ListViewItem item = new ListViewItem(row[0].ToString());
    for (int i = 1; i < dt.Columns.Count; i++)
        {
        item.SubItems.Add(row[i].ToString());
        }
    myListView.Items.Add(item);
    }


这篇关于如何从excel复制数据并粘贴到lisview中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆