带彩色单元格的DataGridView到Excel
本文关键字:Excel DataGridView 彩色 单元格 | 更新日期: 2023-09-27 18:25:16
我看了很多例子和演示,但我看不到
我正在尝试将datagridview转换为excel。
我的结果https://i.stack.imgur.com/x6WlF.png
但它变成了这样的优秀https://i.stack.imgur.com/3iK5a.png
我想复制单元格的大小和颜色,但如何复制?
我用这个代码转换成excel
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
Int16 i, j;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (i = 0; i <= dataGridView1.RowCount - 2; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
xlWorkSheet.Cells[i + 1, j + 1] = dataGridView1[j, i].Value.ToString();
}
}
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.xls)|*.xls";
sfd.FileName = listBox1.SelectedItem.ToString() + " " + listBox3.SelectedItem.ToString() + " Stok Reçeteleri" + ".xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
//ToCsV(dataGridView1, sfd.FileName); // Here dataGridview1 is your grid view name
xlWorkBook.SaveAs(sfd.FileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
//xlWorkBook.SaveAs(sfd.FileName, Excel.XlFileFormat.X
FileInfo fileInfo = new FileInfo(sfd.FileName);
}
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
将内部循环更新为:
for (i = 0; i <= dataGridView1.RowCount - 2; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
Range range = (Range)xlWorkSheet.Cells[i + 1, j + 1];
xlWorkSheet.Cells[i + 1, j + 1] = dataGridView1[j, i].Value.ToString();
range.Interior.Color = System.Drawing.ColorTranslator.ToOle(dataGridView1.Rows[i].DefaultCellStyle.BackColor );
}
}
别忘了:
using Microsoft.Office.Interop.Excel;
请参阅:
使用C#更改Cells的背景
尝试使用此代码导出到excel,而不是您正在使用的代码。不过,我在网络应用程序中使用了这个。
private void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "SomeFileName" + DateTime.Now + ".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
GridView1.GridLines = GridLines.Both;
GridView1.HeaderStyle.Font.Bold = true;
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}