明輝手游網(wǎng)中心:是一個免費提供流行視頻軟件教程、在線學習分享的學習平臺!

用C#迅速往Excel寫數(shù)據(jù)

[摘要]本示例是用于將ListView中的內(nèi)容倒入到Excel與常用的逐單元格寫不同的是,本例子采用數(shù)據(jù)寫入到range的方法。該方法效率明顯較高Excel.Application app = new Excel.ApplicationClass(); if( app == null) M...
本示例是用于將ListView中的內(nèi)容倒入到Excel

與常用的逐單元格寫不同的是,本例子采用數(shù)據(jù)寫入到range的方法。該方法效率明顯較高

Excel.Application app = new Excel.ApplicationClass();
   if( app == null)
   {
    MessageBox.Show("Excel無法啟動");
    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 = {"標題1","標題2","標題3",
         "標題4","標題5","標題6",
         "標題7","標題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;