自定义从delphi导入的excel文件

自定义从delphi导入的excel文件,excel,delphi,delphi-7,dbgrid,Excel,Delphi,Delphi 7,Dbgrid,我编写了一个代码从dbgrid导出excel文件。以下是代码: var i, x:integer; sfile:string; begin XlApp:=createoleobject('Excel.Application'); XlBook:=XlApp.WorkBooks.Add; XlSheet:= XlBook.worksheets.add; for i:=0 to dbgrid1.fieldcount-1 do begin xlsheet.cells[1,i+1].value:

我编写了一个代码从dbgrid导出excel文件。以下是代码:

    var i, x:integer;
sfile:string;
begin
XlApp:=createoleobject('Excel.Application');
XlBook:=XlApp.WorkBooks.Add;
XlSheet:= XlBook.worksheets.add;
for i:=0 to dbgrid1.fieldcount-1 do begin
xlsheet.cells[1,i+1].value:=dbgrid1.columns[i].title.caption;
end;
zquery1.first;
x:=1;
while not zquery1.eof do begin
xlsheet.cells[x+1,1].value:=x;
for i:=1 to dbgrid1.fieldcount-1 do begin
xlsheet.cells[x+1, i+1].value:=dbgrid1.fields[i].text;
end;
zquery1.next;
inc(x);
end;
xlapp.visible:=true;
end;
它很好用,但是桌子太乱了。 如何自定义此excel文件,使每列根据每个数据给出正确的宽度值?
谢谢。

您可以使用
列[i]设置每列的宽度。ColumnWidth

var
  ColRange: Variant;

ColRange := xlsheet.Columns;
ColRange.Columns[1].ColumnWidth := 12;

Excel
Range
有一个
AutoFit
方法,可以在一次调用中为您完成此操作,并且不需要您通过实验来确定需要为每个列指定的宽度

下面是一个示例(在Delphi 2007中测试),它创建了一个二维变量数组,用太宽而无法容纳默认Excel单元格的示例文本填充该数组,将该文本指定给Excel范围,并将该范围内的所有单元格自动宽度设置为文本的适当宽度(类似于双击Excel中列之间的分隔符时所发生的情况)。您应该能够轻松地采用这种方式来自动调整文本宽度(以及通过自动化将数据传输到Excel中的更快方式),以使用代码

出于演示目的,我将代码放入
TButton.OnClick
事件处理程序中

uses
  ComObj, ActiveX;

procedure TForm3.Button1Click(Sender: TObject);
var
  xls, wb, Range: OLEVariant;
  arrData: Variant;
  RowCount, ColCount, i, j: Integer;
begin
  {create variant array where we'll copy our data}
  RowCount := 10;
  ColCount := 10;
  arrData := VarArrayCreate([1, RowCount, 1, ColCount], varVariant);

  {fill array}
  for i := 1 to RowCount do
    for j := 1 to ColCount do
      arrData[i, j] := Format('This is test text #%d-%d', [i, j]);

  {initialize an instance of Excel}
  xls := CreateOLEObject('Excel.Application');

  {create workbook}
  wb := xls.Workbooks.Add;

  {retrieve a range where data must be placed}
  Range := wb.WorkSheets[1].Range[wb.WorkSheets[1].Cells[1, 1],
                                  wb.WorkSheets[1].Cells[RowCount, ColCount]];

  { copy data from the array into an Excel Range, and then use AutoFit to size them }
  Range.Value := arrData;
  Range.Columns.AutoFit;

  {show Excel with our data}
  xls.Visible := True;
end;

非常感谢!我不擅长编码,所以有很多属性我都不知道!我实际上也在尝试格式化我的单元格值。我正在尝试colrange.columns[1]。numberformat:='#,0',但它不起作用。有什么想法吗?没关系,我找到了它!我使用的不是'#,0',##0',它可以工作。Excel COM API有文档记录。在那里找到答案。