Tuesday, August 11, 2009

Export Data from Listview to 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)
{
}
}
...

No comments:

Post a Comment

Followers