Формирование диаграммы Excel из Delphi
Всем доброго дня Помогите пожалуйста со следующей задачей - по данным организации (отгрузки и оплаты) нужно сформировать диаграмму в екселе. БД в Sql server , структура таблицы с данными по отгрузкам и оплатам следующая:
Отгрузки | Оплаты | Дата_операции
По шкале x должна выводится дата операции но получается просто линия и цифры, т.е. дат там никаких не выводится. Во вложении выложил какая получается диаграмма. Подскажите пожалуйста в чем проблема может быть и как она решается.
Программный код как формируется диаграмма:
PHP код:
procedure TOtgruZki.BitBtn3Click(Sender: TObject); const lcid = LOCALE_USER_DEFAULT; var XL: TExcelApplication; WB: TExcelWorkbook; ASheet: TExcelWorksheet; {$ifdef D7} LastCell: ExcelRange; {$else} LastCell: Range; {$endif} AChart: _Chart; B: TBookMark; R, C: Integer; repData: Variant; begin XL := TExcelApplication.Create(Self); WB := TExcelWorkbook.Create(Self); ASheet := TExcelWorksheet.Create(Self); try XL.Connect; WB.ConnectTo(XL.Workbooks.Add(EmptyParam, lcid)); ASheet.ConnectTo(XL.ActiveSheet as ExcelWorksheet); asheet.Columns.ColumnWidth:=20; ASheet.Range['A1', EmptyParam].Value := 'Название'; ASheet.Range['B1', EmptyParam].Value := 'Отгрузки'; ASheet.Range['C1', EmptyParam].Value := 'Оплаты'; ASheet.Range['D1', EmptyParam].Value := 'Дата_операции';
R := 1; with dm.OTGRUZ_Query3 do begin B := GetBookmark; DisableControls; repData := VarArrayCreate([1, RecordCount, 1, Fields.Count-2], varVariant); try First; // чтение данных из датасэта в массив "вариант" while not Eof do begin for C := 0 to Fields.Count - 3 do repData[R, C + 1] := Fields[C].Value; Inc(R); Next; end; // запись данных в лист ASheet.Range['A2', ASheet.Cells.Item[RecordCount + 1, Fields.Count-2]].Value := repData; VarClear(repData); finally if Assigned(B) then begin if BookmarkValid(B) then GoToBookmark(B); FreeBookmark(B); end; EnableControls; end; end; // последняя ячейка LastCell := ASheet.Range['B2', EmptyParam].SpecialCells(xlCellTypeLastCell, EmptyParam); // постройка диаграммы в отдельном листе (по-умолчанию) AChart := WB.DefaultInterface.Charts.Add(EmptyParam, ASheet.DefaultInterface, 1, // кол-во диаграмм EmptyParam, lcid) as _Chart; AChart.Name := 'Отчет'; // имя листа диаграммы AChart.ChartType := xlLineMarkers; // тип диаграммы // задаем диапозон данных (можно все задать вручную) AChart.SetSourceData(ASheet.Range['B1', ASheet.Cells.Item[LastCell.Row, LastCell.Column]], xlColumns);
if Sender = BitBtn3 then begin // изменяем локацию и внедряем в наш лист! AChart := AChart.Location(xlLocationAsObject, ASheet.Name); with ASheet.Shapes.Item((ASheet.ChartObjects as ChartObjects).Count) do begin Left := ASheet.Range['B1:D1', EmptyParam].Width + 5; Top := 8; Width := 700; Height := 400; end; ASheet.Range['B1', EmptyParam].Select; end;
// серии можно добавлять "вручную": // (AChart.SeriesCollection(EmptyParam, lcid) as SeriesCollection).NewSeries; { (AChart.SeriesCollection(EmptyParam, lcid) as SeriesCollection) .Source: OleVariant; Rowcol: XlRowCol; SeriesLabels: OleVariant; CategoryLabels: OleVariant; Replace: OleVariant); }
with AChart do begin // украшательства диаграммы HasTitle[lcid] := True; ChartTitle[lcid].Characters[EmptyParam, EmptyParam].Text := 'Отчет по отгрузкам/оплатам организации'; with (Axes(xlCategory, xlPrimary, lcid) as Axis) do begin HasTitle := True; AxisTitle.Characters[EmptyParam, EmptyParam].Text := 'Месяц'; end; (Axes(xlValue, xlPrimary, lcid) as Axis).HasTitle := False; with (Axes(xlCategory, xlPrimary, lcid) as Axis) do begin HasMajorGridlines := False; HasMinorGridlines := True; end; with (Axes(xlValue, xlPrimary, lcid) as Axis) do begin HasMajorGridlines := True; HasMinorGridlines := False; end; if Sender = BitBtn4 then Deselect(lcid); // "отвыделим" диаграмму... end;
// устанавливаем примочки для лейблов диаграммы (* AChart.ApplyDataLabels( {Type_} xlDataLabelsShowValue, {LegendKey} False, {AutoText} True, {HasLeaderLines} True, lcid); *)
// можно пробежаться по каждой серии... (* for i := 1 to (AChart.SeriesCollection(EmptyParam, lcid) as SeriesCollection).Count do ; (AChart.SeriesCollection(i, lcid) as Series).ApplyDataLabels( {Type_} xlDataLabelsShowNone, {LegendKey} False, {AutoText} True, {HasLeaderLines} False); *)
// поменяем цвет линии и маркеров у первой серии with (AChart.SeriesCollection(1, lcid) as Series) do begin with Border do begin Color := clBlue; // синий Weight := xlMedium; end; MarkerForegroundColor := clBlue; MarkerBackgroundColor := clBlue; MarkerStyle := xlSquare; MarkerSize := 7; end; // у второй серии... with (AChart.SeriesCollection(2, lcid) as Series) do begin with Border do begin Color := clGreen; Weight := xlMedium; LineStyle := xlDash; end; MarkerForegroundColor := clGreen; MarkerBackgroundColor := clGreen; MarkerStyle := xlSquare; MarkerSize := 7; end;
// убираем легенду
// AChart.HasLegend[lcid] := False;
with AChart.PlotArea[lcid].Border do begin Weight := xlHairline; LineStyle := xlAutomatic; end; AChart.PlotArea[lcid].Interior.ColorIndex := xlAutomatic;
if Sender = BitBtn3 then begin XL.ActiveWindow.Zoom := 90; // 75% XL.ActiveWindow.DisplayWorkbookTabs := False; // спрячем ярлыки страниц end; finally FreeAndNil(ASheet); FreeAndNil(WB); XL.Visible[lcid] := True; FreeAndNil(XL); end;
end;
Последний раз редактировалось windaws, 23.01.2010 в 18:22.
|