删除数据表中的列

我正在导出一个数据表成功的excel表…在该Excel表中,我必须显示除最后一列之外的数据表的列(customerid,Productname,referenceno)….现在我怎样才能显示数据表在Excel中没有显示最后一列(referenceno)…

任何人告诉我这个问题的解决scheme..在此先感谢..

这里是我的代码导出数据表excel:

System.Data.DataTable dt = clsobj.convert_datagrid_orderlist_to_datatable(dvgorderlist, txtreferenceno); oxl = new Excel.Application(); oxl.Visible = true; oxl.DisplayAlerts = false; wbook = oxl.Workbooks.Add(XlWBATemplate.xlWBATWorksheet); oxl.ActiveCell.set_Item(2, 4, "Alfa Aesar"); wsheet = (Excel.Worksheet)wbook.ActiveSheet; wsheet.Name = "Customers"; Excel.Range range = wsheet.get_Range("A6", "H6"); wsheet.get_Range("A6", "H6").Font.Name = "Times new Roman"; wsheet.get_Range("A6", "H6").Font.Size = 12; wsheet.get_Range("A6", "H6").Interior.Color = ConvertColour(Color.SkyBlue); oxl.ActiveWindow.DisplayGridlines = false; int rowCount = 5; foreach (DataRow dr in dt.Rows) { rowCount += 1; for (int i = 1; i < dt.Columns.Count + 1; i++) { // Add the header the first time through if (rowCount == 7) { wsheet.Cells[6, i] = dt.Columns[i - 1].ColumnName; } wsheet.Cells[rowCount, i] = dr[i - 1].ToString(); Excel.Range cellRange = (Range)wsheet.Cells[rowCount, i]; //cellRange.Interior.Color = 200; //cellRange.Interior.Color = ConvertColour(Color.LightBlue); cellRange.Cells.Borders.LineStyle = BorderStyle.FixedSingle; } } cells = wsheet.get_Range(wsheet.Cells[2, 2], wsheet.Cells[rowCount, dt.Columns.Count]); cells.EntireColumn.AutoFit(); wsheet = null; cells = null; 

在你的陈述改变这一行

  for (int i = 1; i < dt.Columns.Count + 1; i++) 

与这一个

 var filteredColumns = dt.Columns.OfType<DataColumn>() .Where( x=> x.ColumnName != "referenceno" ); foreach (var column in filteredColumns ) { //do whatever you want //if you need the index you can create counter and increase it by 1 each loop } 

不要忘记使用linq

 using System.Linq ; 

你试过了吗

 dt.Columns.Remove[dt.Columns.Count - 1]; 
 foreach (DataColumn dc in dt.Columns) { bool deleteIt = true; foreach (StringDictionary sd in sdArray) { if (dc.ColumnName.Equals(sd["Name"])) deleteIt = false; } if (deleteIt) data.Columns.Remove(dc); } 

sdArray包含您在Excel工作表中所需的所有列。 如果你喜欢,你可以使用正常的string[]来代替。 我使用了一个StringDictionaries数组,因为每行都有更多的信息,比如宽度。

Linq对于这类任务也非常棒,但上面的例子只支持一行。 所以我想我们需要一些多样性。

尝试Worksheet.get_Range("rangeVal", "rangeVal").EntireColumn.Hidden = true;

dt.Columns.Remove [ColumnIndex];

要么

dt.Columns.Remove [ “的ColumnName”];

尝试任何…