Добавить строку в существующий документ Excel со стилями - PullRequest
0 голосов
/ 19 июля 2010

Я работаю с C # 2008 (FW 3.5), OpenXML SDK 2.0 и документами Excel 2007.

Программа берет значения из базы данных и создает динамическую таблицу, а значения вставляются вШаблон Excel.

Все это хорошо, но мне нужно кое-что еще:

Мне нужно создать указанное количество новых строк в шаблоне, но со стилями (border, font, backcolor и т. Д.)..) а я не знаю, как это сделать.

Кто-нибудь может мне помочь с примером кода для этого?

Большое спасибо и извините за мой английский.

Ответы [ 2 ]

0 голосов
/ 29 ноября 2010

Rastro,

Для этого можно использовать следующий метод

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 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
0 голосов
/ 20 июля 2010

У меня была такая же ситуация, и я не нашел ничего лучше, но использую макрос vb в документе Excel, который добавляет новую строку и вызывает ее из .net.

...