Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted
Comments
Nelek 14-Dec-13 11:58am    

1 solution

First, connect to Excel, and read the spreadsheet into a DateTable
Pretty simple:
C#
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);
    DataTable dt = new DataTable();
    da.Fill(dt);
    con.Close();
    con.Dispose();
    return dt;
    }

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:
C#
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);
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900