Delphi 对文件的操作
导出excel、
//导出excel procedure TForm1.btn3Click(Sender: TObject); var i: integer; excel: OleVariant; saveDialog: TSaveDialog; sFileName: string; begin try try excel := createoleobject('excel.Application'); except excel := createoleobject('excel.sheet.12'); end; excel.workbooks.Add; except Application.MessageBox('无法调用Excel!', '警告', MB_ok + MB_iconwarning); end; saveDialog := TSaveDialog.Create(nil); saveDialog.Filter := '文件excel(.xls)|.xls|文件excel(.xlsx)|.xlsx'; if saveDialog.execute then begin if FileExists(saveDialog.FileName) then begin try if Application.MessageBox('该文件已存在是否覆盖?', '询问', MB_YESNO + MB_iconwarning) = IDYES then begin DeleteFile(PChar(saveDialog.FileName)); end else begin excel.Quit; saveDialog.Free; Exit; end; except excel.Quit; saveDialog.Free; Exit; end; end; sFileName := saveDialog.FileName; end; saveDialog.Free; if sFileName = '' then begin excel.Quit; Exit; end; excel.cells.Font.size := 5; // 字大小 excel.columns.HorizontalAlignment := 2; // 对齐方式 for i := 1 to 3 do excel.ActiveSheet.columns[i].ColumnWidth := 20; // 设置格宽度 excel.cells[1, 1] := '2第一行第一列'; excel.cells[1, 2] := '2第一行第二列'; excel.cells[1, 3] := '2第一行第三列'; excel.cells[2, 1] := '2第二行第一列'; excel.cells[2, 2] := '2第二行第二列'; excel.cells[2, 3] := '2第二行第三列'; try if (copy(sFileName, length(sFileName) - 4, 5) <> '.xlsx') then begin sFileName := sFileName + '.xlsx'; end; // 保存 excel.ActiveWorkbook.SaveAs(sFileName, 51, '', '', False, False); // 51是xlsx -4143是xls except excel.Quit; screen.cursor := crDefault; Exit; end; // 打开显示 excel.Visible := True; end;
//导入excel
导入excel
procedure TForm1.btn4Click(Sender: TObject);
var
i : integer;
excel : Variant;
openDialog : TOpenDialog;
sFileName : string;
sValue : string;
iValue : integer;
begin
//打开路径
opendialog := TOpenDialog.Create(nil);
openDialog.InitialDir := ExtractFilePath(Application.ExeName);
openDialog.Filter :='.xls文件|.xls|.xlsx文件|.xlsx';
openDialog.DefaultExt := 'xls'; //当用户未输入文件扩展名时它用于指明默认的扩展名。
openDialog.Title := '打开excel';
openDialog.FileName := '';
if openDialog.execute then
begin
edt1.Text := openDialog.FileName;
end;
openDialog.Free;
sFileName := Trim(edt1.Text);
if sFileName='' then
begin
Exit;
end;
// 取数据
try
try
excel := CreateOleObject('excel.Application');
except
excel := CreateOleObject('excel.sheet.12');
end;
except
Application.MessageBox('无法调用Excel!', '警告', MB_ok + MB_iconwarning);
end;
excel.Visible := False;
excel.workbooks.open(sFileName);
excel.worksheets[1].Activate;
sValue := excel.cells[1,1].value;
Memo1.Lines.Append('数据:' + sValue);
iValue := excel.worksheets[1].UsedRange.Rows.Count;
Memo1.Lines.Append('行数:' + IntToStr(iValue));
iValue := excel.worksheets[1].usedRange.columns.Count;
Memo1.Lines.Append('列数: '+ IntToStr(iValue));
excel.activeWorkBook.Close;
excel.quit;
excel := Unassigned;
end;