如何按标题名称删除excel列?

时间:2017-11-08 15:42:10

标签: c# excel winforms windows-applications worksheet

我正在做一个c#windows应用程序项目。它将读取所有excel标头并粘贴到checkedListBox。选中checkedListBox后的项目。它将从excel中删除列标题和行(例如您点击excel的标题列并按删除按钮)

你可以帮助我吗?'(

Select header name for delete

Dalete this column Display result



public void OpenFile()
        {
            Excel excel = new Excel(@"D:\Book2.xlsx", 1);

            for(int i = 0; i <= 4; i++)
            {
               
                label1.Text = "Total : " + i.ToString() + " Column";

                
                label2.Text = excel.ReadCell(0, i);
                checkedListBox1.Items.Insert(i, label2.Text);
            }


      
        }
&#13;
&#13;
&#13;

&#13;
&#13;
class Excel
    {
        string path = "";
        _Application excel = new _Excel.Application();
        Workbook wb;
        Worksheet ws;

        public Excel(string path, int Sheet)
        {
            this.path = path;
            wb = excel.Workbooks.Open(path);
            ws = wb.Worksheets[Sheet];
        }

        public string ReadCell(int i, int j)
        {
            i++;
            j++;
            if(ws.Cells[i, j].Value2 != null)
            {
                return ws.Cells[i, j].Value2;
            }
            else
            {
                return "";
            }
        }
    }
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您正在使用哪个Excel框架/库?

您是否尝试过:

using OfficeOpenXml;
...
ws.DeleteColumn(Int32 columnIndex);

您可以将事件处理程序附加到: https://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.itemcheck(v=vs.110).aspx

使用CheckBox的Tag属性来传递Column索引。

类似的东西:

checkedListBox1.ItemCheck += CheckedListBox1_ItemCheck;

private void CheckedListBox1_ItemCheck(Object sender, ItemCheckEventArgs e) {
CheckBox checkedBox = (CheckBox) sender;
Int32 columnIndex = (Int32) checkedBox.Tag;

ws.DeleteColumn(columnIndex);

}