我正在使用C#2008(FW 3.5),OpenXML SDK 2.0和Excel 2007文档。
程序从数据库获取值并创建动态表,并将值粘贴到Excel模板中。
所有这些工作都很好,但我需要别的东西:
我需要在模板中创建指定数量的新行,但是使用样式(边框,字体,背景颜色等)并且我不知道如何制作它。
有人可以帮我提供一个示例代码吗?
非常感谢,请原谅我的英语。
答案 0 :(得分:0)
我有同样的情况,没有发现更好,但在excel文档中使用vb宏,添加新行并从.net调用它。
答案 1 :(得分:0)
斯特罗,
您可以使用以下方法执行此操作
private UInt32Value createBorder(Stylesheet styleSheet,bool buttomBorderDouble)
{
Border border;
//set borders of header
if (buttomBorderDouble)
{
border = new Border
(
new BottomBorder { Style = BorderStyleValues.Double },
new DiagonalBorder());
}
else
{
border = new Border
(
new BottomBorder {Style = BorderStyleValues.Thin},
new DiagonalBorder());
}
styleSheet.Borders.Append(border);
UInt32Value result = styleSheet.Borders.Count;
styleSheet.Borders.Count++;
return result;
}
private UInt32Value createFont(Stylesheet styleSheet, string fontName, Nullable<double> fontSize, bool isBold, System.Drawing.Color foreColor, bool isUnderLine)
{
Font font = new Font();
if (!string.IsNullOrEmpty(fontName))
{
FontName name = new FontName()
{
Val = fontName
};
font.Append(name);
}
if (fontSize.HasValue)
{
FontSize size = new FontSize()
{
Val = fontSize.Value
};
font.Append(size);
}
if (isBold == true)
{
Bold bold = new Bold();
font.Append(bold);
}
if (isUnderLine == true)
{
Underline underline = new Underline();
font.Append(underline);
}
if (foreColor != null)
{
Color color = new Color()
{
Rgb = new HexBinaryValue()
{
Value =
System.Drawing.ColorTranslator.ToHtml(
System.Drawing.Color.FromArgb(
foreColor.A,
foreColor.R,
foreColor.G,
foreColor.B)).Replace("#", "")
}
};
font.Append(color);
}
styleSheet.Fonts.Append(font);
UInt32Value result = styleSheet.Fonts.Count;
styleSheet.Fonts.Count++;
return result;
}
private UInt32Value createCellFormat(Stylesheet styleSheet, UInt32Value fontIndex, UInt32Value fillIndex, UInt32Value numberFormatId, UInt32Value borderId)
{
CellFormat cellFormat = new CellFormat();
if (fontIndex != null)
cellFormat.FontId = fontIndex;
if (fillIndex != null)
cellFormat.FillId = fillIndex;
if (numberFormatId != null)
{
cellFormat.NumberFormatId = numberFormatId;
cellFormat.ApplyNumberFormat = BooleanValue.FromBoolean(true);
}
if (borderId != null)
cellFormat.BorderId = borderId;
styleSheet.CellFormats.Append(cellFormat);
UInt32Value result = styleSheet.CellFormats.Count;
styleSheet.CellFormats.Count++;
return result;
}
及其一段调用这些方法的代码
样式表styleSheet = workbook.WorkbookStylesPart.Stylesheet;
UInt32Value headerFontIndex =
createFont(
styleSheet,
"MS Sans Seif",
10,
true,
System.Drawing.Color.Black, false);
UInt32Value doubleBorderIndex = createBorder(styleSheet, true);
UInt32Value headerStyleIndexWithDoubleBottomBorder =
createCellFormat(
styleSheet,
headerFontIndex,
0,
null, doubleBorderIndex);
Cell _Cell = createTextCell(1, 1, "Intercompany Reconciliation Summary", headerStyleIndexWithDoubleButtomBorder, null);
输出结果是写下公司间对帐汇总,下面加粗线和双线
我希望它可以帮到你
Thanks, Mohammed Thabet Zaky Software Developer Cairo,Egypt