如何使用 Interop C# 隐藏 Excel 列和行

How to hide Excel Columns and Rows using Interop C#

我制作了一个简单的库存界面,它将从访问中获取数据并显示在我界面上的数据网格视图中,然后通过单击按钮将信息发送到 Excel。这部分根据需要工作,但我想在发送信息后删除未使用的列和行。我目前正在使用 VS 2015。我不知道要添加什么来完成这个。

//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();
            }
        }
    }

您的问题有点过于宽泛,因此答案很笼统:要删除整个工作表列,您可以使用 VBA 语句,例如:Columns("C").Delete, or Columns(3).EntireColumn.Delete,或 Columns("F:K").Delete。类似的语法可能适用于:Rows(3).Delete.

为了仅隐藏 Rows/Columns 使用如下所示的 VBA 语句:

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

希望这可能有所帮助。