procedure Tfm1.Stringgridtoexcel(atitle:string;Astringgrid: Tstringgrid; Afontsize: integer);
var xlapp, xlsheet: variant;
row, CCC, nnn, jjj: integer;
begin
try
xlapp := createoleobject(‘excel.application‘);
except
showmessage(‘not found excel in your system, so can not create file!‘);
exit;
end;
try
ccc := Astringgrid.ColCount;
xlapp.workbooks.add; //添加新工作簿
xlapp.visible := false;
xlsheet := xlapp.activesheet;
xlapp.activewindow.windowstate := 2;
xlapp.range[xlsheet.cells[1, 1], xlsheet.cells[1, ccc]].MERGE;
xlsheet.cells[1, 1].value := Atitle; //页头第一行;
xlsheet.cells[1, 1].HorizontalAlignment := -4108;
row := 2;
for jjj := 0 to Astringgrid.RowCount - 1 do
begin
for nnn := 1 to ccc do
xlsheet.cells[row, nnn] := trim(Astringgrid.Cells[nnn - 1, row - 2]);
xlsheet.rows[row].RowHeight := 18;
inc(row);
end;
xlapp.visible := true;
//格式调整
xlapp.range[xlsheet.cells[row, 1], xlsheet.cells[row, 13]].WrapText := True;
xlapp.range[xlsheet.cells[row, 1], xlsheet.cells[row, 13]].HorizontalAlignment := -4108;
xlsheet.pagesetup.headerMargin := 1 / 0.035; //页眉到顶端边距1cm
xlsheet.pagesetup.footerMargin := 0.6 / 0.035; //页脚到底端边距1cm
xlsheet.pagesetup.topMargin := 1 / 0.035; //顶边距1cm
XLSHEET.pagesetup.bottomMargin := 1.3 / 0.035; //底边距1cm
xlsheet.pagesetup.leftMargin := 0.5 / 0.035; //左边距1cm
xlsheet.pagesetup.rightMargin := 0.5 / 0.035; //右边距1cm
xlsheet.pagesetup.leftfooter := ‘制表: ‘ + ‘制表人‘;
xlsheet.pagesetup.centerfooter := ‘‘; //页脚
xlsheet.pagesetup.rightfooter := ‘第&P页/共&N页‘;
xlsheet.pagesetup.leftHeader := ‘‘;
xlsheet.pagesetup.orientation := 1; //横向
xlsheet.pagesetup.printtitlerows := ‘$1:$1‘;
xlsheet.rows[1].font.name := ‘宋体‘; //设置第一行字体属性
xlsheet.rows[1].font.bold := true;
xlsheet.rows[1].font.size := 20;
xlsheet.rows[1].RowHeight := 28;
for nnn := 1 to ccc do
begin
xlsheet.columns[nnn].columnwidth := Astringgrid.ColWidths[nnn - 1] * 0.1188;
end;
for nnn := 1 to 4 do begin
xlapp.range[xlsheet.cells[2, 1], xlsheet.cells[row - 1, CCC]].borders[nnn].linestyle := 1;
xlapp.range[xlsheet.cells[2, 1], xlsheet.cells[row - 1, CCC]].borders[nnn].weight := 1;
end;
xlapp.range[xlsheet.cells[2, 1], xlsheet.cells[row - 1, CCC]].font.size := Afontsize;
xlapp.range[xlsheet.cells[2, 1], xlsheet.cells[row - 1, ccc]].WrapText := True;
varclear(xlsheet);
varclear(xlapp);
except
on E: Exception do
begin
xlapp.quit;
showmessage(‘出现错误‘+E.message);
end;
end;
end;