hi guys, it took me some time to find out how to export listview to excel, so i wanted to share it with you. i would like to post this thread as code snippet but in that section there is no attachment button that i can attach project to. i show two ways of exporting, one with assuming that excel is installed on the target machine, the other is with assuming excel is not installed so i chose to export as comma delimited csv file.

Form1.cs :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ListViewToExcel
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			
			for (int i = 0; i < 10; i++)
			{
				myList.Columns.Add(i.ToString());	
				ListViewItem lv = new ListViewItem(i.ToString());
				for (int ai = 0; ai < 10; ai++)
				{
					lv.SubItems.Add(ai.ToString());
				}
				myList.Items.Add(lv);
			}

		}

		private void btnExcel_Click(object sender, EventArgs e)
		{
			Excel.Application app = new Excel.Application();
			app.Visible = true;
			Excel.Workbook wb = app.Workbooks.Add(1);
			Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
			int i = 1;
			int i2 = 1;
			foreach (ListViewItem lvi in myList.Items)
			{
				i = 1;
				foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
				{
					ws.Cells[i2, i] = lvs.Text;
					i++;
				}
				i2++;
			}
		}

		private void btnCsv_Click(object sender, EventArgs e)
		{
			saveFileDialog1.Filter = "csv files (*.csv)|*.csv";
			saveFileDialog1.FileName = "logs";
			saveFileDialog1.Title = "Export to Excel";
			StringBuilder sb = new StringBuilder();
			foreach (ColumnHeader ch in myList.Columns)
			{
				sb.Append(ch.Text + ",");
			}
			sb.AppendLine();
			foreach (ListViewItem lvi in myList.Items)
			{
				foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
				{
					if (lvs.Text.Trim() == string.Empty)
						sb.Append(" ,");
					else
						sb.Append(lvs.Text + ",");
				}
				sb.AppendLine();
			}
			DialogResult dr = saveFileDialog1.ShowDialog();
			if (dr == DialogResult.OK)
			{
				StreamWriter sw = new StreamWriter(saveFileDialog1.FileName);
				sw.Write(sb.ToString());
				sw.Close();
			}
		}
	}
}

Form1.Designer.cs :

namespace ListViewToExcel
{
	partial class Form1
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			
			this.myList = new System.Windows.Forms.ListView();
			this.btnExcel = new System.Windows.Forms.Button();
			this.btnCsv = new System.Windows.Forms.Button();
			this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
			this.SuspendLayout();
			
			// 
			// myList
			// 
			this.myList.Location = new System.Drawing.Point(29, 37);
			this.myList.Name = "myList";
			this.myList.Size = new System.Drawing.Size(637, 232);
			this.myList.TabIndex = 0;
			this.myList.UseCompatibleStateImageBehavior = false;
			this.myList.View = System.Windows.Forms.View.Details;
			// 
			// btnExcel
			// 
			this.btnExcel.Location = new System.Drawing.Point(29, 8);
			this.btnExcel.Name = "btnExcel";
			this.btnExcel.Size = new System.Drawing.Size(75, 23);
			this.btnExcel.TabIndex = 1;
			this.btnExcel.Text = "Excel";
			this.btnExcel.UseVisualStyleBackColor = true;
			this.btnExcel.Click += new System.EventHandler(this.btnExcel_Click);
			// 
			// btnCsv
			// 
			this.btnCsv.Location = new System.Drawing.Point(122, 8);
			this.btnCsv.Name = "btnCsv";
			this.btnCsv.Size = new System.Drawing.Size(75, 23);
			this.btnCsv.TabIndex = 2;
			this.btnCsv.Text = "CSV";
			this.btnCsv.UseVisualStyleBackColor = true;
			this.btnCsv.Click += new System.EventHandler(this.btnCsv_Click);
			// 
			// Form1
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(691, 290);
			this.Controls.Add(this.btnCsv);
			this.Controls.Add(this.btnExcel);
			this.Controls.Add(this.myList);
			this.Name = "Form1";
			this.Text = "Form1";
			this.Load += new System.EventHandler(this.Form1_Load);
			this.ResumeLayout(false);

		}

		#endregion

	
		private System.Windows.Forms.ListView myList;
		private System.Windows.Forms.Button btnExcel;
		private System.Windows.Forms.Button btnCsv;
		private System.Windows.Forms.SaveFileDialog saveFileDialog1;




	}
}

the project is attached to this post. notice that excel object libraries 11 is referenced.

if you want to save the excel file then modify the code as follows :

private void btnExcel_Click(object sender, EventArgs e)
		{
			Excel.Application app = new Excel.Application();
			app.Visible = true;
			Excel.Workbook wb = app.Workbooks.Add(1);
			Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
			int i = 1;
			int i2 = 1;
			foreach (ListViewItem lvi in myList.Items)
			{
				i = 1;
				foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
				{
					ws.Cells[i2, i] = lvs.Text;
					i++;
				}
				i2++;
			}
	wb.SaveAs(@"C:\TEMP\myExcel.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing,
				Type.Missing, Type.Missing);
			wb.Close(false,Type.Missing,Type.Missing);
			app.Quit();
		}

finally, i added a smart export button, which enables you to export your listview and save it as .xls or .csv file.

private void btnExport_Click(object sender, EventArgs e)
		{
			
			saveFileDialog1.Filter = "excel files (*.xls)|*.xls | csv files (*.csv)|*.csv";
			if (saveFileDialog1.ShowDialog() == DialogResult.OK)
			{
				if (saveFileDialog1.FilterIndex == 1)
				{
					Excel.Application app = new Excel.Application();
					Excel.Workbook wb = app.Workbooks.Add(1);
					Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
					int i = 1;
					int i2 = 1;
					foreach (ListViewItem lvi in myList.Items)
					{
						i = 1;
						foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
						{
							ws.Cells[i2, i] = lvs.Text;
							i++;
						}
						i2++;
					}
					wb.SaveAs(saveFileDialog1.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing,
				Type.Missing, Type.Missing);
					wb.Close(false, Type.Missing, Type.Missing);
					app.Quit();
				}
				else if (saveFileDialog1.FilterIndex == 2)
				{
					StringBuilder sb = new StringBuilder();
					foreach (ColumnHeader ch in myList.Columns)
					{
						sb.Append(ch.Text + ",");
					}
					sb.AppendLine();
					foreach (ListViewItem lvi in myList.Items)
					{
						foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
						{
							if (lvs.Text.Trim() == string.Empty)
								sb.Append(" ,");
							else
								sb.Append(lvs.Text + ",");
						}
						sb.AppendLine();
					}
					StreamWriter sw = new StreamWriter(saveFileDialog1.FileName);
					sw.Write(sb.ToString());
					sw.Close();
				}
				
			}
		}

i attached the final state of project to this post.

i attached the final state of project to this post.

I really appreciate the code you've added for this! I have downloaded your project but the Excel namespace doesn't appear to be valid. Am I missing a reference? I see you mention the excel object libraries 11 in the previous post, but I am not familiar with what that means.
Please forgive me if this is a stupid question!!
I appreciate any help you can provide.

Thanks,
kworcester

y porque no salen las cabeceras??

I think below article may help you much,it uses a third library which can export data from databse, command, listview to excel ,word, pdf,html, xml, ms access, csv etc.
Export Data from Listview to Excel with C#
When you applycing the code in this article, after adding Spire.DataExport dll please make sure that you add two namespaces:
using Spire.DataExport.TXT;
using Spire.DataExport.XLS;

It works fine in my project, hope it can help you.

Encontre esto, con esto solucione en parte mi consulta.

try
            {
                Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
                xla.Visible = true;
                Microsoft.Office.Interop.Excel.Workbook wb = xla.Workbooks.Add(Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
                Microsoft.Office.Interop.Excel.Worksheet ws = ((Microsoft.Office.Interop.Excel.Worksheet)xla.ActiveSheet);

                int i = 1;
                int j = 1;
                int jj = lsvListaCamposActivos.Columns.Count;

                for (int rr = 0; rr < jj; rr++)
                {
                    ws.Cells[i, j] = lsvListaCamposActivos.Columns[rr].Text;
                    j = j + 1;
                }
                i = 2;
                j = 1;
                foreach (ListViewItem lista in lsvListaCamposActivos.Items)
                {
                    ws.Cells[i, j] = lista.Text.ToString();
                    foreach (ListViewItem.ListViewSubItem drv in lista.SubItems)
                    {
                        ws.Cells[i, j] = drv.Text.ToString();
                        j += 1;
                    }
                    j = 1;
                    i += 1;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.