如何在从datagridview复制粘贴到excel时保持颜色

本文关键字:excel 颜色 datagridview 复制 | 更新日期: 2023-09-27 18:21:28

我使用以下CellFormatting代码有条件地为数据网格视图中的行着色。

private void SGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == SGridView.Columns["Name"].Index )
    {
        DataGridViewRow row = SGridView.Rows[e.RowIndex];
        SBomRow BomRow = (SBomRow )row.DataBoundItem;
        switch (BomRow.UsageType())
        {
            case (UsageType.NE):
                break;
            case (UsageType.SV):
                e.CellStyle.BackColor = Color.OrangeRed;
                break;
            case (UsageType.Mix):
                e.CellStyle.BackColor = Color.LightGray;
                break;
            default:
                break;
        }
    }
}

当我从datagridview复制粘贴到excel时,颜色会丢失。我知道数据在粘贴时会作为HTML和CSV数据添加到剪贴板,所以在粘贴到excel时可能不可能保持着色。这是真的吗,或者有没有一种方法可以在复制粘贴时保持颜色。

如何在从datagridview复制粘贴到excel时保持颜色

我相信DataGridView默认情况下只在剪贴板中存储制表符分隔的数据,而不格式化

但是您可以使用中描述的方法编写自定义的带有格式的复制函数

http://www.tcx.be/blog/2005/copy-html-to-clipboard/

万一你想问一个问题,如何处理复制事件来写一些自定义代码并将格式化的HTML放入剪贴板,我建议使用PreviewKeyDown事件并写一些类似的东西

if (e.KeyData.ToString() == "C, Control") {  your formatting code goes here  
} 

我可以通过使用此处代码的修改版本来设置颜色。首先,我将CopyHtmlToClipBoard()更改为公共静态void方法,并将其放置在Extension类中。接下来,在调用代码时,我设置了一个var来捕获每个单元格的颜色,然后修改html。AppendFormat()语句,以包含要传递的颜色。这是所用代码的副本:

 public static void CopyHtmlToClipBoard(string html)
    {
        Encoding enc = Encoding.UTF8;
        string begin = "Version:0.9'r'nStartHTML:{0:000000}'r'nEndHTML:{1:000000}"
          + "'r'nStartFragment:{2:000000}'r'nEndFragment:{3:000000}'r'n";
        string html_begin = "<html>'r'n<head>'r'n"
          + "<meta http-equiv='"Content-Type'""
          + " content='"text/html; charset=" + enc.WebName + "'">'r'n"
          + "<title>HTML clipboard</title>'r'n</head>'r'n<body>'r'n"
          + "<!--StartFragment-->";
        string html_end = "<!--EndFragment-->'r'n</body>'r'n</html>'r'n";
        string begin_sample = String.Format(begin, 0, 0, 0, 0);
        int count_begin = enc.GetByteCount(begin_sample);
        int count_html_begin = enc.GetByteCount(html_begin);
        int count_html = enc.GetByteCount(html);
        int count_html_end = enc.GetByteCount(html_end);
        string html_total = String.Format(
          begin
          , count_begin
          , count_begin + count_html_begin + count_html + count_html_end
          , count_begin + count_html_begin
          , count_begin + count_html_begin + count_html
          ) + html_begin + html + html_end;
        DataObject obj = new DataObject();
        obj.SetData(DataFormats.Html, new MemoryStream(
          enc.GetBytes(html_total)));
        Clipboard.SetDataObject(obj, true);
    }

     private void copyAlltoClipboard()
    {
        var DataGridView1Counts = DataGridView1.Rows.Count;

        StringBuilder html = new StringBuilder();
        html.Append("<table>");
        if (DataGridView1Counts > 0)
        {
            //sets headers
            html.Append("<tr>");
            html.Append("<th> Name1 </th>");
            html.Append("<th> Name2 </th>");
            html.Append("<th> Name3 </th>");
            html.Append("<th> Name4 </th>");
            html.Append("<th> Name5 </th>");
            foreach (DataGridViewRow row in DataGridView1.Rows)
            {
                html.Append("<tr>");
                foreach (DataGridViewCell cell in row.Cells)
                {
                    var cellcolor = cell.Style.BackColor;
                    html.AppendFormat("<td bgcolor = " + cellcolor.Name + ">{0}</td>", cell.Value);
                }
                html.Append("</tr>");
            }
        }
        html.Append("</table>");
        Extensions.CopyHtmlToClipBoard(html.ToString());
    }