有没有人知道如何通过C#将数据复制到Excel中的表格范围而不会丢失表格格式?
每次我将数据复制到范围时,它都会丢失先前设置的格式。
private object[,] Get2DArrayData()
{
var obj = new object[2, 4];
obj[0, 0] = "Header1";
obj[0, 1] = "Header2";
obj[0, 2] = "Header3";
obj[0, 3] = "Header4";
obj[1, 0] = 1;
obj[1, 1] = 2;
obj[1, 2] = 3;
obj[1, 3] = 4;
return obj;
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
var worksheet = Globals.ThisAddIn.Application.ActiveSheet;
Range range = worksheet.Range["A1:D2"];
Excel.ListObject obj = worksheet.ListObjects.Add(Excel.XlListObjectSourceType.xlSrcRange, range, null, Excel.XlYesNoGuess.xlYes, null);
obj.TableStyle = "TableStyleMedium3";
obj.Name = "MyTableNamedRange";
//table style is lost after setting Value2 on the range
range.Value2 = Get2DArrayData();
}
每次我将数组数据粘贴到Value2时,ListObject都会被清除。有没有办法不丢失这种格式?在添加到ListObjects属性之前设置Value2属性是不可能的。
答案 0 :(得分:0)
如果要使用数据填充ListObject,则应将ListObject的HeaderRowRange和DataBodyRange设置为内容数组:
obj.HeaderRowRange.Value2 = /* Your array with table headers goes here */
obj.DataBodyRange.Value2 = /* Your array with table data goes here */