This example is used to import the content in ListView to Excel. Unlike the commonly used cell-by-cell writing, this example uses the data Writing Method to range. This method is more efficient.
Excel. Application app = new Excel. ApplicationClass ();
If (app = null)
{
MessageBox. Show ("Excel cannot be started ");
Return;
}
App. Visible = true;
Excel. Workbooks wbs = app. Workbooks;
Excel. Workbook wb = wbs. Add (Missing. Value );
Excel. Worksheet ws = (Excel. Worksheet) wb. Worksheets [1];
Excel. Range r = ws. get_Range ("A1", "H1 ");
Object [] objHeader = {"Title 1", "title 2", "Title 3 ",
"Title 4", "Title 5", "Title 6 ",
"Title 7", "Title 8 "};
R. Value = objHeader;
If (lv. Items. Count> 0)
{
R = ws. get_Range ("A2", Missing. Value );
Object [,] objData = new Object [this. lv. Items. Count, 8];
Foreach (ListViewItem lvi in lv. Items)
{
ObjData [lvi. Index, 0] = lvi. Text;
ObjData [lvi. Index, 1] = lvi. SubItems [1]. Text;
ObjData [lvi. Index, 2] = lvi. SubItems [2]. Text;
ObjData [lvi. Index, 3] = lvi. SubItems [3]. Text;
ObjData [lvi. Index, 4] = lvi. SubItems [4]. Text;
ObjData [lvi. Index, 5] = lvi. SubItems [5]. Text;
ObjData [lvi. Index, 6] = lvi. SubItems [6]. Text;
ObjData [lvi. Index, 7] = lvi. SubItems [7]. Text;
}
R = r. get_Resize (lv. Items. Count, 8 );
R. Value = objData;
R. EntireColumn. AutoFit ();
}
App = null;