C# 如何使用COM简介将彩色表格添加到Excel?
这是我使用COM互操作生成Excel的代码C# 如何使用COM简介将彩色表格添加到Excel?,c#,excel-interop,C#,Excel Interop,这是我使用COM互操作生成Excel的代码 public static void ExportDataTableToExcel(DataTable dt, string filepath) { object missing = Type.Missing; object misValue = System.Reflection.Missing.Value; //create excel Microsoft.Office.Inte
public static void ExportDataTableToExcel(DataTable dt, string filepath)
{
object missing = Type.Missing;
object misValue = System.Reflection.Missing.Value;
//create excel
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
//add excel workbook
Microsoft.Office.Interop.Excel.Workbook wb = excel.Workbooks.Add();
//add worksheet to worlbook
Microsoft.Office.Interop.Excel.Worksheet ws = wb.Sheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
//Set the header-row bold
ws.Range["A1", "A1"].EntireRow.Font.Bold = true;
//Adjust all columns
ws.Columns.AutoFit();
//spit top row
ws.Application.ActiveWindow.SplitRow = 1;
//freeze top row
ws.Application.ActiveWindow.FreezePanes = true;
int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
ws.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
ws.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
wb.SaveAs(@"C:\ErangaExcelTest.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue,
misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive, misValue,
misValue, misValue, misValue, misValue);
wb.Close(missing, missing, missing);
excel.Quit();
}
公共静态void ExportDataTableToExcel(DataTable dt,字符串文件路径)
{
对象缺失=类型。缺失;
对象错误值=System.Reflection.Missing.Value;
//创建excel
Microsoft.Office.Interop.Excel.Application Excel=新的Microsoft.Office.Interop.Excel.Application();
//添加excel工作簿
Microsoft.Office.Interop.Excel.Workbook wb=Excel.Workbooks.Add();
//将工作表添加到工作簿
Microsoft.Office.Interop.Excel.Worksheet ws=wb.Sheets[1]作为Microsoft.Office.Interop.Excel.Worksheet;
//将标题行设置为粗体
ws.Range[“A1”,“A1”]。EntireRow.Font.Bold=true;
//调整所有列
ws.Columns.AutoFit();
//吐上一排
ws.Application.ActiveWindow.SplitRow=1;
//冻结顶行
ws.Application.ActiveWindow.FreezePanes=true;
int rowCount=1;
foreach(数据行dr在dt.行中)
{
行计数+=1;
对于(int i=1;i
这是我从这个方法得到的Excel
我需要一张像这样色彩鲜艳的桌子
如果有这种彩色Excel,我需要做什么样的修改?您需要为每个单元格设置字体颜色和背景颜色。您已通过以下方式将字体设置为粗体:
ws.Range["A1", "A1"].EntireRow.Font.Bold = true;
现在字体对象具有更多属性。要设置字体颜色,请使用。要设置单元格的背景色,请参见。具体来说,您需要将图案
设置为xlPatternSolid
,然后使用内部
对象的颜色
属性设置一些颜色
在VBA中,可以使用字体的RGB值指定字体:
range.Font.Color = RGB(255, 0, 0)
将范围的字体颜色设置为红色
要更改边框,请使用。该链接有一个如何使用的示例代码。是否可以加粗表格边框?更新了答案,提供了如何设置边框的信息。