简体   繁体   English

C#Interop Excel格式,如Excel的格式为表格

[英]C# Interop Excel format like Excel's format as table

I'm exporting a table from SQLite to Excel (2010) in C# . 我正在使用C#将表格从SQLite导出到Excel (2010)。 It works fine. 它工作正常。 I'm using the Excel.Range.set_Value() method. 我正在使用Excel.Range.set_Value()方法。

How can I format an Excel.Range like Excel's format (like a table) would? 如何格式化Excel.RangeExcel's格式(如表格)?

To expand upon my comment and add to D Stanley. 扩展我的评论并添加到D Stanley。

Range range = ws.get_Range("A1:D5");
wrksheet.ListObjects.AddEx(XlListObjectSourceType.xlSrcRange, range, missing, Microsoft.Office.Interop.Excel.XlYesNoGuess.xlNo, missing).Name = "MyTableStyle";
wrksheet.ListObjects.get_Item("MyTableStyle").TableStyle = "TableStyleMedium1";

This example selects a rectangular range of every cell in the active sheet. 此示例选择活动工作表中每个单元格的矩形范围。 Also, it uses indexed parameters of Range to get the range points. 此外,它使用Range的索引参数来获取范围点。 Furthermore, AddEx() (and most methods in Interop.Excel) uses default parameters so you don't have to use System.Reflection.Missing. 此外,AddEx()(以及Interop.Excel中的大多数方法)使用默认参数,因此您不必使用System.Reflection.Missing。

// define points for selecting a range
// point 1 is the top, leftmost cell
Excel.Range oRng1 = oSheet.Range["A1"];
// point two is the bottom, rightmost cell
Excel.Range oRng2 = oSheet.Range["A1"].End[Excel.XlDirection.xlToRight]
    .End[Excel.XlDirection.xlDown];

// define the actual range we want to select
oRng = oSheet.Range[oRng1, oRng2];
oRng.Select(); // and select it

// add the range to a formatted table
oRng.Worksheet.ListObjects.AddEx(
    SourceType: Excel.XlListObjectSourceType.xlSrcRange,
    Source: oRng,
    XlListObjectHasHeaders: Excel.XlYesNoGuess.xlYes);

Here's the VBA that does it: 这是VBA:

ActiveSheet.ListObjects.Add xlSrcRange, Range("$J$10:$N$12"), , xlYes

Shouldn't be too hard to translate into an automation call. 不应该太难转化为自动化调用。 You can read the documentation as well. 您也可以阅读文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM