Formatowanie komorek excela

0

Mam taki fragment kodu:

unit Unit1;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComObj, StdCtrls;
type
  TForm1 = class(TForm)
   Button1: TButton;
   procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
var
  Form1: TForm1;
implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
      Excel: Variant;
begin
    Excel:=CreateOleObject('Excel.Application');
    Excel.SheetsInNewWorkbook := 2;
    Excel.application.workbooks.ADD;
    Excel.Cells[1,2].Value:=('Przykladowy tekst');
    Excel.Visible:=true;
end;
end.

Chciał bym zrobić formatowanie komórek z Delphi 6 a dokładnie:
-kolor tła
-obramowanie
-wyrównanie tekstu
-kąt obrotu tekstu
-zmiana szczerokości kolumny
-zmiana wysokości wiersza

proszę o podanie odpowiednich instrukcji, z góry dzięki

0

Zarejestruj makro w VBA, rób to co potrzebujesz, potem zobacz na kod makra. Zobacz też kod poniżej. Procedurka robi ramkę, zmienia kolor, rozmiar, centrowanie itp.

procedure TMain.btExportClick(Sender: TObject);
var
 lcid   :Integer;
 VarArr :Variant;
 i, j   :Byte;
 k, w   :Byte;
 v      :single;
 s      :string;
begin
  try
    lcid := GetUserDefaultLCID();
    xlApp.Visible[lcid] := True;
    xlApp.ScreenUpdating[lcid] := False;
    xlApp.DisplayAlerts[lcid] := false;

    xlWB.ConnectTo(xlApp.Workbooks.Add(EmptyParam, lcid));
    xlWS.ConnectTo(xlWB.Worksheets[1] as _Worksheet);
    xlWS.Name := 'Tabela kątów';

    // ustawienia wydruku
    with xlWS.PageSetup do
    begin
      Orientation := xlLandScape;
      CenterHorizontally := true;
      CenterVertically := true;
      PaperSize := xlPaperA4;
      Zoom := False;
      FitToPagesWide := 1;
      FitToPagesTall := 1;
    end;

    with SG do
    begin
      k := ColCount;
      w := RowCount;

      VarArr := VarArrayCreate([1, w, 1, k], varVariant);
      for i := 1 to w do
        for j := 1 to k do
          begin
            s := Cells[j - 1, i - 1];
            if TryStrToFloat(s, v) then
               VarArr[i, j] := v else
               VarArr[i, j] := s
          end;
    end;

    // kopiowanie tabeli
    with xlWS.Range[xlWS.Cells.Item[2,1], xlWS.Cells.Item[w+1, k]] do
    begin
      Value2 := VarArr;
      Font.ColorIndex := 16;
      Font.Italic := True;

      FormatConditions.Delete;
      FormatConditions.Add(xlCellValue, xlBetween,
                          (FloatToStr(MinA)),
                          (FloatToStr(MaxA)));
      FormatConditions[1].Interior.ColorIndex := 8;
      FormatConditions[1].Font.Bold := True;
      FormatConditions[1].Font.ColorIndex := 0;

      Columns.HorizontalAlignment := xlCenter;

      // obramowanie
      Borders[xlEdgeLeft].LineStyle := xlContinuous;
      Borders[xlEdgeTop].LineStyle := xlContinuous;
      Borders[xlEdgeBottom].LineStyle := xlContinuous;
      Borders[xlEdgeRight].LineStyle := xlContinuous;
      Borders[xlInsideVertical].LineStyle := xlContinuous;
      Borders[xlInsideHorizontal].LineStyle := xlContinuous;
    end;

    // cell formating
    with xlWS.Range[xlWS.Cells.Item[3,2], xlWS.Cells.Item[w+1, k-1]] do
    begin
      NumberFormat := '0'+DecimalSeparator+'00';
    end;

    // title
    with xlWS.Range[xlWS.Cells.Item[1,1], xlWS.Cells.Item[1, k]] do
    begin
      Merge(xlCenter);
      Cells.HorizontalAlignment := xlCenter;
      Cells.ColumnWidth := Length(SG.Cells[1,1]);
      Cells.Item[1,1] := cbPartNames.Text;
      Font.Size := 18;
    end;

    // fixed col left
    with xlWS.Range[xlWS.Cells.Item[2,1], xlWS.Cells.Item[w+1, 1]] do
    begin
      Interior.ColorIndex := 15;
      Interior.Pattern := xlSolid;
      Font.Bold := True;
      Font.Italic := False;
      Font.ColorIndex := 0;
    end;

    // fixed col rght
    with xlWS.Range[xlWS.Cells.Item[2,k], xlWS.Cells.Item[w+1, k]] do
    begin
      Interior.ColorIndex := 15;
      Interior.Pattern := xlSolid;
      Font.Bold := True;
      Font.Italic := False;
      Font.ColorIndex := 0;
    end;

    // fixed row
    with xlWS.Range[xlWS.Cells.Item[2,1], xlWS.Cells.Item[2, k]] do
    begin
      Interior.ColorIndex := 15;
      Interior.Pattern := xlSolid;
      Font.Bold := True;
      Font.Italic := False;
      Font.ColorIndex := 0;
    end;

    // autor
    with xlWS.Range[xlWS.Cells.Item[w+1,1], xlWS.Cells.Item[w+1, k]] do
    begin
      if edExecutor.Text = '' then
         Cells.Item[1,1] := 'Opracował:'+StringOfChar(' ', 20)+
                            ' Dnia: '+DateToStr(Now())
      else
         Cells.Item[1,1] := 'Opracował: <'+edExecutor.Text+
                            '>, Dnia: '+DateToStr(Now());

      Merge(xlCenter);
      Cells.HorizontalAlignment := xlRight;
    end;

    xlApp.ScreenUpdating[lcid] := True;

    xlApp.DisplayAlerts[lcid] := true;
    xlWS.Disconnect();
    xlWB.Disconnect();
    xlApp.Disconnect();
  except
    MessageBox(Main.Handle,
               'Błąd połączenia z MS Excel / '#13+
               'MS Excel connection error',
               'Error',
               MB_OK or MB_ICONERROR);
  end;
end;
0

Ale mnie to nie działa kompilatora nie przyjmuje np. xlContinuous i tego xlEdgeLeft i wielu innych? czy trzeba jeszcze coś zadeklarować??

0

bo to są stałe symboliczne zdefiniowane w Excel2000

0
remik86 napisał(a)

Chciał bym zrobić formatowanie komórek z Delphi 6 a dokładnie:
-kolor tła
-obramowanie
-wyrównanie tekstu
-kąt obrotu tekstu
-zmiana szczerokości kolumny
-zmiana wysokości wiersza

Przykład na szybko:

procedure TForm1.Button3Click(Sender: TObject);
var
        Sheet, Excel: Variant;
begin
        //Otwarcie nowego Excela - widoczny dla użytkownika
        Excel := CreateOleObject('Excel.Application');
        Excel.Visible := True;

        Excel.WorkBooks.Add(); //Stworzenie (dodanie) skoroszytu (standardowego - trzy arkusze)
        Excel.WorkBooks[1].WorkSheets.Add(); //Stworzenie (dodanie) arkusza (czwartego)

        //Przypisanie do zmiennej - patrz niżej
        Sheet := Excel.WorkBooks[1].WorkSheets[1];
        Sheet.Name := 'Test';
        //Po nadaniu nazwy można też tak: Excel.WorkBooks[1].WorkSheets['Test'] - ale po co?

        //Odwoływanie się do konkretnej komórki
        Sheet.Cells[1, 1].Value := '11'; //Zapis danej do komórki Excela - liczba
        Sheet.Cells[1, 2].Value := '''rybka'; //Zapis danej do komórki Excela - string
        Sheet.Cells[1, 3].Value := '=A1*3'; //Zapis danej do komórki Excela - formuła

        //Odwoływanie się do zakresu i formatowanie wyglądu
        Sheet.Range['A1:AA1'].Font.Bold := True; //Pogrubienie
        Sheet.Range['A1:AA1'].Font.Color := clBlue; //Kolor czcionki
        Sheet.Range['A1:K1'].Borders.LineStyle := 13; //Styl linii
        Sheet.Range['A1:K11'].HorizontalAlignment := 3; //Wyrównanie w poziomie - centralnie

        //Ustawianie szerokości kolumn
        Sheet.Columns[1].ColumnWidth := 10;
        Sheet.Columns[2].ColumnWidth := 10;
        Sheet.Columns[3].ColumnWidth := 15;
        Sheet.Columns[4].ColumnWidth := 6;
        Sheet.Columns[5].ColumnWidth := 18;
        Sheet.Columns[6].ColumnWidth := 9;
        Sheet.Columns[7].ColumnWidth := 23;
        Sheet.Columns[8].ColumnWidth := 23;
        Sheet.Columns[9].ColumnWidth := 23;

        //Zmiana tytułu głównego okna, jeśli to komu potrzebne
        Excel.Caption := 'Automatyzacja Excela z poziomu Delphi...';

        //Zatrzymanie wykonywania, potem wyjście
        ShowMessage('ExceloZatrzymywacz! :] Zobacz efekty (w tle) i kliknij OK tutaj, aby zamknąć Excela...');
        Excel.DisplayAlerts := False; //Nie pytaj o zapis niezapisanych
        Excel.Quit;
end;

Jeśli potrzeba Ci więcej, to polecam pogooglowanie:
http://www.google.com/search?q=Delphi%20and%20Microsoft%20Office:%20Automating%20Excel%20and%20Word

0

I jeszcze jeden fragmencik kodu w temacie formatowanie komórek i inne "zabawy" z Excelem.

procedure TForm1.Button4Click(Sender: TObject);
var
        i, j: Integer;
        Range, Sheet, Sheets: Variant;
const
        xlWorksheet = -4167;
        xlContinuous = $00000001;
begin
        //Initiate Delphi random generator;
        Randomize();

        //Call up Excel, add one workbook with one sheet and give it a name
        XLApplication := CreateOleObject('Excel.Application');
        XLApplication.Visible := True;
        XLApplication.Workbooks.Add(xlWorksheet);
        XLApplication.Workbooks[1].WorkSheets[1].Name := 'Random by Delphi';

        //Make assignment and fill sheet with random numbers
        Sheet := XLApplication.Workbooks[1].WorkSheets['Random by Delphi'];
        for i := 1 to 25 do for j := 1 to 6 do Sheet.Cells[i, j] := Random;

        //The Cells property works exactly as you would expect,
        //except Excel puts the Row first and the Column second.

        //Add another sheet and force Excel to fill it with random numbers
        //It is also an example of more complex assignment
        Sheets := XLApplication.Sheets;
        Sheets.Add(, Sheets.Item[1], 1, xlWorkSheet);
        Sheets.Item[2].Name := 'Random by Excel';
        Range := Sheets.Item[2].Range['A1:F25'];

        //If you're using localized version of Excel (i.e. Polish), you
        //HAVE TO supply formulas IN ENGLISH even so; they'll be translated
        //to proper language by Excel itself (to =LOS() in this example)
        //Here is also an example of accessing formulas directly, not
        //by passing strings to cells - eariler examples
        Range.Formula := '=RAND()';

        //And do some extra formating
        Range.Columns.Interior.ColorIndex := 3;
        //You can use the Excel help to see the values in the ColorIndex;
        //first few default values are: black, white, red, green, blue,
        //yellow, purple, cyan; Note that you CAN'T use delphi color codes
        //(i.e. clTeal) as you would do in second example (Formatowanie)

        //As you change the color, you also loose your borders. This is
        //a peculiarity of Excel, and it can be worked around by resetting
        //the LineStyle of the selected cells
        Range.Borders.LineStyle := xlContinuous;

        //To find more constants, import Excel_TLB via Project >
        //Import Type Library and serach in created PAS file
end;
0

Nekrofil....

0

To teraz ja mam pytanko. Jak do diabła zmienić GRUBOŚĆ linii (serii) na wykresie? Szlag mnie trafia, bo Excel 2007 domyślnie daje grubość 2,25 punkta, która jest stanowczo za gruba dla mnie.

W Delphi + Excel umiem dość sporo jeśli chodzi o wykresy. Oto przykład dla kogoś szukającego podstaw:

procedure TForm1.Button7Click(Sender: TObject);
var
        DataRange, Chart, Sheet: Variant;
        i: Integer;
const
        xlFreeFloating = $00000003;
        xlXYScatterSmoothNoMarkers = $00000049;
        xlMarkerStyleNone = $FFFFEFD2;
        xlLegendPositionBottom = $FFFFEFF5;
begin
        //Initiate Delphi random generator;
        Randomize();
        
        //Call up Excel, add one workbook with one sheet and give it a name
        XLApplication := CreateOleObject('Excel.Application');
        XLApplication.Visible := True;
        XLApplication.DisplayAlerts := False;
        XLApplication.Workbooks.Add(xlWorksheet);
        XLApplication.Workbooks[1].Sheets[1].Name := 'Data';

        //Select proper worksheet
        Sheet := XLApplication.Workbooks[1].Sheets['Data'];

        //Fill some random data
        for i := 1 to 3 do Sheet.Cells[1, i + 1] := 'Param ' + IntToStr(i);

        for i := 1 to 10 do
        begin
                Sheet.Cells[i + 1, 1] := Now() - i + 1 + Random;
                Sheet.Cells[i + 1, 1].NumberFormat := 'rrrr-mm-dd gg:mm:ss';
                Sheet.Cells[i + 1, 2] := Random;
                Sheet.Cells[i + 1, 3] := Random;
                Sheet.Cells[i + 1, 4] := Random;
        end;

        //Add chart inside worksheet and give it a name
        Sheet.Shapes.AddChart.Name := 'chrt1';

        //You can access chart by name or by index
        //This example shows relative sizing and positioning of a chart
        //Force chart to be placed in exactly specified row and column
        //and have width and height relative to exactly specified number of rows or columns
        Sheet.ChartObjects('chrt1').Left := Sheet.Columns.Columns[5].Left;
        Sheet.ChartObjects('chrt1').Top := Sheet.Rows.Rows[1].Top;
        Sheet.ChartObjects(1).Width := Sheet.Columns.Columns[10].Left;
        Sheet.ChartObjects(1).Height := Sheet.Rows.Rows[28].Top;

        //Make it floating - i.e. don't move or resize along with cells underneath it...
        Sheet.ChartObjects(1).Placement := xlFreeFloating;

        //Example of accessing chart inside chartobject object
        Chart := Sheet.ChartObjects(1).Chart;

        //Set title and legend
        Chart.HasTitle := True;
        Chart.ChartTitle.Text := 'Delphi-Excel Automation Chart Example';
        Chart.ChartType := xlXYScatterSmoothNoMarkers;
        Chart.HasLegend := True;
        Chart.Legend.Position := xlLegendPositionBottom;

        //Delete all automatically added Series
        for i := Chart.SeriesCollection.Count downto 1 do
                Chart.SeriesCollection(i).Delete;

        //Add new series and format it
        //Two ways of achieving it. One - by range selection:
        //DataRange := XLApplication.Union(Sheet.Range['A1:A11'], Sheet.Range['C1:C11']);
        //Chart.SeriesCollection.Add(DataRange, 2, True, True, False);
        //Two: by relative cells numbers (usefull in loops):
        for i := 1 to 3 do
        begin
                Chart.SeriesCollection.NewSeries;
                Chart.SeriesCollection(i).XValues := '=Data!R2C1:R11C1';
                Chart.SeriesCollection(i).Values := '=Data!R2C' + IntToStr(i + 1) + ':R11C' + IntToStr(i + 1);
                Chart.SeriesCollection(i).Name := 'Parametrek ' + IntToStr(i); // Addressing like '=Data!R1C2' for Name does DOESN'T work in Delphi 5!
                Chart.SeriesCollection(i).Smooth := False;
                Chart.SeriesCollection(i).MarkerStyle := xlMarkerStyleNone;
        end;

        //Add trendline - if you need one
        //Chart.SeriesCollection(1).Trendlines.Add(xlLinear, 'Linear Trend');
end;

Ale grubości linii nie da się zmienić w ten sposób, albo ja jestem ślepy. Próbowałem różnych sposobów. Grzebałem w pliku pomocy do Excel 2007 Visual Basic, szukałem w necie, nawet próbowałem odpalić makro w Excelu. I nic. Makro nie rejestruje takiej opercji, jak zmiana grubości linii (serii danych) na wykresie. Gdyby ktoś miał jakiś pomysł - byłbym wdzięczny.

0

No i sam sobie odpowiadam. Może się to komuś przyda...

var
        Excel, Chart, DataRange: Variant;
begin
        Excel := CreateOleObject('Excel.Application');
        Excel.Visible := True;
        Excel.Charts.Add.Activate;
        Chart := Excel.ActiveChart;
        DataRange := Sheet.Range['A1:A10'];
        Chart.SeriesCollection.Add(DataRange, 2, True, False, False);
        Chart.SeriesCollection(1).Border.Weight := xlThin;
end;

Ostatnia linijka rozwiązuje problem...

0

Dzięki. Włąśnie walczę z Excelem - Twoje podpowiedzi są bardzo cenne.

0

Witam.

Ja mam pytanko jak wyciągnąć z Excela informację o wyrównaniu tekstu?
kiedy zadaję ustawienie tekstu:
excel.cells[wr,4].HorizontalAlignment:=2;
wszystko jest ok i w excelu tekst wyrównuje mi się jak należy. Ale kiedy używamy argumentu w instrukcji warunkowej:
if (excel.cells[wr,4].HorizontalAlignment=2) then ...
to niestety Delphi nie jest w stanie wyciągnąć tej informacji i instrukcja warunkowa się nigdy nie wykona. Nawet gdy uprzednio programowo ustawię zadaną wartość na danym polu to nie chce mi jej odczytać.

1 użytkowników online, w tym zalogowanych: 0, gości: 1