我使用以下CellFormatting代码有条件地为我的datagridview中的行着色。
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时可能无法保持着色。这是真的,还是有一种方法可以在复制粘贴时保持颜色。
答案 0 :(得分:1)
我相信默认情况下DataGridView只在剪贴板中存储制表符分隔数据而不格式化
但您可以使用
中描述的方法编写自定义使用格式化复制功能http://www.tcx.be/blog/2005/copy-html-to-clipboard/
如果你想问一个问题如何处理复制事件以编写一些自定义代码并将格式化的HTML放到剪贴板中,我建议使用PreviewKeyDown事件并编写类似
的内容if (e.KeyData.ToString() == "C, Control") { your formatting code goes here
}
答案 1 :(得分:1)
我可以使用找到的here代码的修改版本来设置颜色。首先,我将CopyHtmlToClipBoard()更改为public static 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());
}