2016-03-13 81 views
3

我製作了一個簡單的庫存界面,它將從訪問中獲取數據並在我的界面上顯示datagrid視圖,然後通過單擊按鈕將信息發送到Excel。這部分根據需要工作,但我想在發送信息後刪除未使用的列和行。我目前正在使用VS 2015.我不知道要添加什麼來實現這一點。如何使用Interop C隱藏Excel列和行#

//send to excel 
    private void btnExport_Click(object sender, EventArgs e) 
    { 
     ActiveControl = txtSerial; 
     // creating Excel Application 
     Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application(); 

     // creating new WorkBook within Excel application 
     Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing); 

     // creating new Excelsheet in workbook 
     Microsoft.Office.Interop.Excel._Worksheet worksheet = null; 

     // see the excel sheet behind the program 
     app.Visible = true; 

     // get the reference of first sheet. By default its name is Sheet1. 
     // store its reference to worksheet 
     worksheet = workbook.Sheets["Sheet1"]; 
     worksheet = workbook.ActiveSheet; 

     // changing the name of active sheet 
     worksheet.Name = "Inventory Search"; 

     // storing header part in Excel 
     for (int i = 1; i < dataGridFB.Columns.Count + 1; i++) 
     { 
      worksheet.Cells[1, i] = dataGridFB.Columns[i - 1].HeaderText; 
      worksheet.Cells[1, i].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightBlue); 
      worksheet.Cells[1, i].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black); 
      worksheet.Cells[1, i].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; 
      worksheet.Cells[1, i].Font.Size = 14; 
     } 

     // storing Each row and column value to excel sheet 
     for (int i = 0; i < dataGridFB.Rows.Count - 1; i++) 
     { 
      for (int j = 0; j < dataGridFB.Columns.Count; j++) 
      { 
       worksheet.Cells[i + 2, j + 1] = dataGridFB.Rows[i].Cells[j].Value.ToString(); 
       worksheet.Cells[i + 2, j + 1].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; 
       worksheet.Cells[i + 2, j + 1].Font.Size = 12; 
       worksheet.Columns["A:G"].AutoFit(); 
      } 
     } 
    } 
+0

你想刪除哪些特定列? –

+0

那麼,我絕對不會使用過去列「E」的任何東西,但行總是不一樣的,一次可以是2個「使用」行,下一行可能是「25」行。 – CamlCase

回答

4

你的問題有點過於寬泛,因此答案是通用:爲了刪除整個工作表列中,您可以使用VBA語句,如:Columns("C").Delete, or Columns(3).EntireColumn.Delete,或者Columns("F:K").Delete。類似的語法可能適用於:Rows(3).Delete

爲了剛剛隱藏的行/列使用VBA語句類似如下所示:

Rows("3:10").EntireRow.Hidden = True 
Columns("C").Hidden = True 

希望這有助於。

+0

未使用的列/行由定義爲空,因此沒有內容並且不需要刪除。你想隱藏它們嗎? –

+0

是的,我想隱藏它們。不好的選擇(刪除) – CamlCase

+0

請參閱我的擴展答案。 –