明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺(tái)!

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

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

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

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