2013-11-27 27 views
0

我想命名excel表格的第一行中的每一列,我在第一列命名列上出現異常。請指教?向excel導出列表視圖中的第1行添加文本

Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application(); 
      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 = 2; 
     int j = 1; 

     if (comboBox1.Text == "Brickcom") 
     { 
      try 
      { 
       ws.Rows[j, 1] = "Category"; 
       ws.Rows[j, 2] = "Part Number"; 
       ws.Rows[j, 3] = "TradePrice"; 
       ws.Rows[j, 4] = "Product"; 
       ws.Rows[j, 5] = "Resolution"; 
       ws.Rows[j, 6] = "Included Accessories"; 
       ws.Rows[j, 7] = "Major Acc Price";    


       foreach (ListViewItem comp in listView1.Items) 
       { 

        ws.Cells[i, j] = comp.Text.ToString(); 

        foreach (ListViewItem.ListViewSubItem drv in comp.SubItems) 
        { 
         ws.Cells[i, j] = drv.Text.ToString(); 

         j++; 
        } 

        j = 1; 
        i++;       
       } 
       xla.Visible = true; 
      } 
      catch 
      { 
       MessageBox.Show("Export did not work"); 
      } 
     } 

回答

0

試試這個:

  ws.Cells[j, 1] = "Category"; 
      ws.Cells[j, 2] = "Part Number"; 
      ws.Cells[j, 3] = "TradePrice"; 
      ... 
+0

效果很好,非常感謝。我不知道爲什麼我沒有想到這一點。 – user3012159

+0

它確定。歡迎:-) – Swati

0

我會用流作家:

SaveFileDialog savefile = new SaveFileDialog(); 
    savefile.Filter = "CSV|*.csv"; 
    savefile.RestoreDirectory = true; 
    savefile.ShowDialog(); 
    string filename = savefile.FileName; 
    if (filename != "") 
    { 
    StreamWriter ofile = new StreamWriter(filename); 
    ofile.WriteLine("Category, Part Number, TradePrice, ..."); //just separate using a comma , 

    //your complete writings here 

    ofile.Close(); //close the streamwriter and you're done 
    } 

好運

相關問題