【问题标题】:How can I export data from Excel to datatable with text color in C#?如何在 C# 中将数据从 Excel 导出到带有文本颜色的数据表?
【发布时间】:2012-07-31 07:02:07
【问题描述】:

我正在尝试在 VS 2010 WinForms 应用程序中使用 C# 将 MS Excel 工作表中的数据导出到数据表中。

我希望根据文本前景色从 Excel 中导出某些行,例如文本颜色为黑色、绿色和红色。如果文本颜色是绿色,那么我想排除该行被导出。

我怎样才能做到这一点?

【问题讨论】:

    标签: c# visual-studio-2010 excel datatable


    【解决方案1】:

    您应该在 Excel 中遍历行并在导出前检查文本颜色。先打开 Excel 文件。

    Microsoft.Office.Interop.Excel.Application App = new Microsoft.Office.Interop.Excel.Application();
    App.Visible = false;
    App.WindowState = Excel.XlWindowState.xlMinimized;
    App.ShowStartupDialog = false;
    
    Excel.Workbook WorkBook = App.Workbooks.Open(File, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
    

    最好先获取正在使用的区域:

    Excel.Range Area = worksheet.get_Range("A1", worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing));
    

    迭代:

    for (int R = 1; R <= Area.Rows.Count; R++)
    {
    Excel.Range Row = ((Excel.Range)Area[R, "A"]);
    if(Row.Font.Color != Excel.XlRgbColor.rgbGreen)
    {
       // Get data from the cells and include into a
       // collection of items that represents data to be exported.
    }
    }
    

    【讨论】:

    • 即使我添加了 Interop.Excel dll 引用和命名空间,我也找不到枚举 Excel.XlRgbColor 实例。
    • 请尝试:使用 Excel = Microsoft.Office.Interop.Excel;
    猜你喜欢
    • 2012-06-25
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多