DBGird中資料匯入Excel例子!

來源:互聯網
上載者:User
部分代碼參考CSDN網站上的文章!
procedure TForm1.BitBtn1Click(Sender: TObject);
var
  ExcelWorksheet: TExcelWorksheet;
  ExcelApplication: TExcelApplication;
  ExcelWorkbook: TExcelWorkbook;
  i, row, column: integer;
  x1,x2,y1,y2 : integer;
begin
  x1 := 1;
  y1 := 2;
  column := 1;
  ExcelApplication := TExcelApplication.Create(Application);
  ExcelWorksheet := TExcelWorksheet.Create(Application);
  ExcelWorkbook := TExcelWorkbook.Create(Application);

  Try
    ExcelApplication.Connect;
  Except
    ShowMessage('Error!');
  End;
  ExcelApplication.Visible[0] := True;
  ExcelApplication.Caption := 'Excel Application';
  ExcelApplication.Workbooks.Add(Null, 0);
  ExcelWorkbook.ConnectTo(ExcelApplication.Workbooks[1]);
  ExcelWorksheet.ConnectTo(ExcelWorkbook.Worksheets[1] as _Worksheet);
  row := 3;
  ExcelWorksheet.Cells.Item[1, 1] := 'XXXXX';   //標題設定
  ExcelWorksheet.Range[ExcelWorksheet.Cells.Item[1,1],
                       ExcelWorksheet.Cells.Item[1,2]].Merge(0);
  ExcelWorksheet.Cells.Item[1,1].HorizontalAlignment:=xlCenter;
  for i:=1 to DBGrid1.Columns.Count do
  begin
    ExcelWorksheet.Cells.Item[2, i] := DBGrid1.Columns.Items[i-1].FieldName;
  end;
  While Not (DBGrid1.DataSource.DataSet.Eof) do
  begin
    column := 1;
    for i := 1 to DBGrid1.Columns.Count do
    begin
      ExcelWorksheet.Cells.Item[row, column] := DBGrid1.DataSource.DataSet.fields[i - 1].AsString;
      column := column + 1;
    end;
    DBGrid1.DataSource.DataSet.Next;
    row := row + 1;
  end;
  y2 := row-1;
  x2 := column-1;
 //資料內容設定
  ExcelWorksheet.Range[ExcelWorksheet.Cells.Item[y1,x1],
                       ExcelWorksheet.Cells.Item[y2,x2]].Font.Name := '宋體';
  ExcelWorksheet.Range[ExcelWorksheet.Cells.Item[y1,x1],
                       ExcelWorksheet.Cells.Item[y2,x2]].Font.Size := 10;
  ExcelWorksheet.Range[ExcelWorksheet.Cells.Item[y1-1,x1],
                       ExcelWorksheet.Cells.Item[y2,x2]].Borders.Color := clBlack;
  ExcelWorksheet.Range[ExcelWorksheet.Cells.Item[y1-1,x1],
                       ExcelWorksheet.Cells.Item[y2,x2]].Borders.LineStyle := xlContinuous;
  ExcelWorksheet.Cells.Item[1,1].Font.Name := '宋體';  //標題字型設定
  ExcelWorksheet.Cells.Item[1,1].Font.Size := 12;
  ExcelWorksheet.Cells.Item[1,1].Font.Bold := True;

  ExcelApplication.Disconnect;
  ExcelApplication.Free;
  ExcelWorksheet.Free;
  ExcelWorkbook.Free;
end;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.