【问题标题】:Export DataGridVeiw to excel in C# with cell background colors使用单元格背景颜色将 DataGridView 导出到 C# 中的 excel
【发布时间】:2015-10-20 09:29:56
【问题描述】:

我在 Winform C# 的 DataGridView 中创建了一个Shift RosterThis 是我从 DataGridView 导出的 excel 工作表屏幕截图。

我需要将 DataGridView 导出到 Excel 工作表,保持字体颜色和背景颜色,我也不想将 DataGridView 的第一列导出到不可见的 excel。

我已使用以下代码将 DataGridView 导出到 Excel。

using (ExcelPackage pck = new ExcelPackage(file))
{
    // Add a new worksheet to the empty workbook
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
    // Load data from DataTable to the worksheet
    ws.Cells["A1"].LoadFromDataTable(((DataTable)gvShift.DataSource), true);
    ws.Cells.AutoFitColumns();

    // Add some styling
    using (ExcelRange rng = ws.Cells[1, 1, 1, gvShift.Columns.Count])
    {
        rng.Style.Font.Bold = true;
        rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
        rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(79, 129, 189));
        rng.Style.Font.Color.SetColor(System.Drawing.Color.White);
    }

请帮帮忙....

【问题讨论】:

  • 您使用什么库或 dll 进行 excel 导出?
  • 我正在使用 Microsoft.Office.Interop.Excel
  • @MianSalmanNasir 也要看看 EPPlus。
  • 那是EPPlus。

标签: c# excel winforms datagridview export-to-excel


【解决方案1】:

你可以使用 cells.interior.color

Range range = 
            oSheet.get_Range("A" + redRows.ToString(), "J"
                                    + redRows.ToString());

    range.Cells.Interior.Color = System.Drawing.Color.Red; 

更多信息请查看Microsoft interop excel to format excel cells

【讨论】:

  • 我需要将 DataGridView 单元格颜色与数据一起导出到 Excel 中。
  • 获取你需要的 gridview 行并读取像 range.Cells.Interior.Color = Gridview1.Row[rowindex].Cells[cellindex].BackColor 这样的背景颜色属性
【解决方案2】:

我得到了解决方案,我只是从我设置颜色的源中查看,将每个单元格或 DataGridView 置于循环中并通过范围,应用颜色。

感谢大家的帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 2013-04-12
    • 2014-02-27
    • 2017-07-19
    • 2016-05-27
    • 1970-01-01
    • 2018-06-15
    相关资源
    最近更新 更多