我有一个返回额外列的存储过程。我无法控制存储过程。我想使用以下表格生成我的工作表:
ws.Cells.LoadFromDataTable(dt, true, OfficeOpenXml.Table.TableStyles.Light8)
如何只输出我想要的列?
我试图找出一个 Linq 查询,但问题是列名不可访问,所以我无法指定我想要的列。
SqlConnection cx = new SqlConnection(util.GetConnectionString());
SqlCommand cmd = new SqlCommand("StoredRept", cx);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter ta = new SqlDataAdapter();
ta.SelectCommand = cmd;
DataTable dt = new DataTable();
ta.Fill(dt);
FileInfo newFile = new FileInfo("c:\temp");
ExcelPackage epp = new ExcelPackage(newFile);
var ws = epp.Workbook.Worksheets.Add("WS");
// here is where I would like to copy certain columns off into another data table but I haven't been able to figure out how
ws.Cells.LoadFromDataTable(dt, true, OfficeOpenXml.Table.TableStyles.Light8);
如有任何帮助,我们将不胜感激。
最佳答案
如果从表中删除一些列是唯一的问题,那很容易解决。尝试这样的事情:
var dt = new DataTable();
dt.Columns.Add("First", typeof(string));
dt.Columns.Add("Second", typeof(string));
dt.Columns.Add("Third", typeof(string));
dt.Columns.Add("Fourth", typeof(string));
dt.Columns.Add("Fifth", typeof(string));
for (var i = 1; i < 6; i++)
{
dt.Rows.Add($"First {i}", $"Second {i}", $"Third {i}",$"Fourth {i}",$"Fifth {i}");
}
//dt.Dump();//If you have linqpad this is handy to dump table to output
//REMOVE THE COLUMNS.
dt.Columns.RemoveAt(1);
dt.Columns.RemoveAt(2);
//dt.Dump();//again in linqpad this dumps table with remaining 3 columns
您可以使用以下方法按名称查找列并将其删除:
var col=dt.Columns["Second"];
dt.Columns.Remove(col);
这是获取包含所需列的列表的 linq 查询。
var lq = (from DataRow r in dt.Rows
select new { First = r[0], Second=r[1], Third=r["Fifth"]}
).ToList();
lq.Dump();
请注意如何使用列索引或名称从行对象中获取值。
关于c# - 指定数据表中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46289218/