how to convert/export listview to excel

Convert listview to excel file format using the following snippet....

call statement:

ConvertListViewtoExcel(lstCustomer, "E:\\EnquiryDetails\\", "Enq_01.xls");



private void ConvertListViewtoExcel(ListView lv,string dirPath,string fileName)
{
try
{
//lv is nothing but the listview control name
string[] st = new string[lv.Columns.Count];
DirectoryInfo di = new DirectoryInfo(dirPath);
if (di.Exists == false)
di.Create();
StreamWriter sw = new StreamWriter(dirPath + fileName, false);
sw.AutoFlush = true;
for (int col = 0; col < lv.Columns.Count; col++)
{
if (col == 0)
{
sw.Write(lv.Columns[col].Text.ToString());
}
else
{
sw.Write("\t" + lv.Columns[col].Text.ToString());
}
}

int rowIndex = 1;
int row = 0;
string st1 = "";
for (row = 0; row < lv.Items.Count; row++)
{
if (rowIndex <= lv.Items.Count)
rowIndex++;

for (int col = 0; col < lv.Columns.Count; col++)
{
if (col == 0 && rowIndex == (rowIndex - 0))
{
if (rowIndex == 2)
{
st1 = "\n" + lv.Items[row].SubItems[col].Text.ToString();
}
else
{
st1 = lv.Items[row].SubItems[col].Text.ToString();

}
}
else
{
st1 = st1 + "\t" + lv.Items[row].SubItems[col].Text.ToString();
}
}
sw.WriteLine(st1);
}
sw.Close();
FileInfo fil = new FileInfo(dirPath + fileName);
if (fil.Exists == true)
MessageBox.Show("Process Completed", "Export to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
}
}


1)How to convert listview to excel file format

2)How to export listview to excel file format

0 comments:

Post a Comment