从datagridview复制和粘贴到Excel工作表时如何包含单元格颜色 [英] How to include cell color when copying and pasting from datagridview to excel sheet
本文介绍了从datagridview复制和粘贴到Excel工作表时如何包含单元格颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在将行复制并粘贴到Excel工作表时,如何复制datagridview中单元格的颜色。截至目前,我只能将单元格值复制到excel。
解决方案
该信息存储在以下范围内:
http://msdn.microsoft.com/en-us/library/4zs9xy29%28v= vs.80%29.aspx [ ^ ]
并设置如下:
rng.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
我认为你可以直接使用solidcolor笔刷,或者从中得到它:
Excel.Range r =(Excel.Range)m_objRange [< span class =code-digit> 2 , 2 ];
System.Drawing.Color col = System.Drawing.ColorTranslator.FromOle(( int )r.Interior.Color);
在此链接中找到答案。感谢作者和指向我的人。数据表或datagridview必须表示为html表。 测试类是此代码的关键。
http://blog.tcx.be/2005/08/copying-html-fragment-to-clipboard.html [ ^ ]
作者给出的复制和格式化数据表的例子不起作用,虽然它有正确的想法。
这是我写的代码和测试复制和格式化datagridview。请注意,我通过将单元格着色为绿色来进行一些格式化。
StringBuilder html = new StringBuilder();
html.Append(< table>);
for(int i = 0; i< = dataGridView1.RowCount - 1; i ++)
{
html.Append(< tr>);
for(int j = 0; j< = dataGridView1.ColumnCount - 1; j ++)
{
DataGridViewCell cell = dataGridView1 [j,i];
html.AppendFormat(< td bgcolor = green> {0}< / td>,cell.Value);
}
html.Append(< / tr>);
}
html.Append(< / table>);
Test.CopyHtmlToClipBoard(html.ToString());
How can I copy also the color of the cell in datagridview when copying and pasting rows to excel sheet. As of now I can only copy the cell values to excel.
解决方案
That information is stored in the range:
http://msdn.microsoft.com/en-us/library/4zs9xy29%28v=vs.80%29.aspx[^]
And is set like this:
rng.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
I think you could get it directly with a solidcolor brush, or from this:
Excel.Range r = (Excel.Range)m_objRange[2, 2]; System.Drawing.Color col = System.Drawing.ColorTranslator.FromOle((int) r.Interior.Color);
Found the answer at this link. Thanks to the author and to the person who pointed me to it. The data table or datagridview has to be represented as a html table. The class "Test" is the key to this code.
http://blog.tcx.be/2005/08/copying-html-fragment-to-clipboard.html[^]
The example given by the author for copying and formatting a data table does not work although it has the right idea.
Here is code I wrote and tested for copying and formatting a datagridview. Take note that I did some formatting by coloring the cells green.
StringBuilder html = new StringBuilder(); html.Append("<table>"); for (int i = 0; i <= dataGridView1.RowCount - 1; i++) { html.Append("<tr>"); for (int j = 0; j <= dataGridView1.ColumnCount - 1; j++) { DataGridViewCell cell = dataGridView1[j, i]; html.AppendFormat("<td bgcolor=green>{0}</td>", cell.Value); } html.Append("</tr>"); } html.Append("</table>"); Test.CopyHtmlToClipBoard(html.ToString());
这篇关于从datagridview复制和粘贴到Excel工作表时如何包含单元格颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文