Export Data from Listview to Excel


This article help about how to Export Data from Listview to Excel

This code snippet is used to export data from your listview to excel. Before export the data you should load the data in listview control. For doing this you should have MS Excel.



private void Export2Excel()
{
try
{
//lvPDF is nothing but the listview control name
string[] st = new string[lvPDF.Columns.Count];
DirectoryInfo di = new DirectoryInfo(@"c:\PDFExtraction\");
if (di.Exists == false)
di.Create();
StreamWriter sw = new StreamWriter(@"c:\PDFExtraction\" + txtBookName.Text.Trim() + ".xls", false);
sw.AutoFlush = true;
for (int col = 0; col < lvPDF.Columns.Count; col++)
{
sw.Write("\t" + lvPDF.Columns[col].Text.ToString());
}

int rowIndex = 1;
int row = 0;
string st1 = "";
for (row = 0; row < lvPDF.Items.Count; row++)
{
if (rowIndex <= lvPDF.Items.Count)
rowIndex++;
st1 = "\n";
for (int col = 0; col < lvPDF.Columns.Count; col++)
{
st1 = st1 + "\t" + "'" + lvPDF.Items[row].SubItems[col].Text.ToString();
}
sw.WriteLine(st1);
}
sw.Close();
FileInfo fil = new FileInfo(@"c:\PDFExtraction\" + txtBookName.Text.Trim() + ".xls");
if (fil.Exists == true)
MessageBox.Show("Process Completed", "Export to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
}
}



Related Articles

Export Data to Excel in CSV format using .NET

Export Data to excel in CSV format. .NET code to export CSV data. Free .NET code to export data to excel. .NET way of exporting data to excel. Explanation of .NET code to export data to excel in CSV.

Client Side Script to Export to Excel 2007

This article explains the work around for Export to Excel 2007. The earlier vbScript we used for Exporting to Excel 2003 relied on HTMLProject which is no more supported in Excel 2007. Here is the work around.

More articles: Export to Excel

Comments

Author: Ivan11 Mar 2010 Member Level: Bronze   Points : 1

Thank you for interesting post. But there is warning when I try to open Excel File - The file you are trying to open, myfile.xls, is in a different format than specified by the file extension. How can I open file without this warning?

Guest Author: Ylmith08 Mar 2013

Hello, this code works perfectly with the configuration [C# 2008, Windows XP, Office 2003] but don`t work with [C# 2008, Windows 7, Office 2010]. Is there any reason that you are aware of?



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: