I have console Delphi application which works with Excell though OLE.
The examle of code is pretty simple
procedure SaveBaseRecordsToFile(BaseName: string; PaymentRecords: TPaymentRecords);
var
i: integer;
Excel: Variant;
begin
try
Excel:=CreateOleObject('Excel.Application');
Excel.DisplayAlerts:=False;
except
on E: Exception do begin
LogWriter.WriteLog(E.ClassName + ': ' + E.Message);
exit;
end;
end;
try
Excel.Workbooks.Add;
//Excel.Worksheets.Add;
Excel.Worksheets[1].Cells[2, 1].Value := 'Account number';
Excel.Worksheets[1].Cells[2, 2].Value := 'Sum';
for i := 0 to Length(PaymentRecords) - 1 do begin
Excel.Worksheets[1].Cells[i + 3, 1].Value := PaymentRecords[i].NUMBER;
Excel.Worksheets[1].Cells[i + 3, 2].Value := PaymentRecords[i].SUMMA;
end;
Excel.ActiveSheet.Name := 'SHEET1';
Excel.Application.Workbooks[1].SaveAs(ExtractFilePath(ParamStr(0)) + BaseName + '.xls', 56);
Excel.Workbooks.Close;
Excel.Quit;
finally
Excel := Unassigned;
end;
end;
When I run this application in interactive mode (by myself) it wors perfect.
But when I try to run it through standart Microsoft Scheduler I see in log of my applications such records:
21:41:40.523: EOleSysError: Отказано в доступе, ProgID: "Excel.Application" (Access denied from Russian)
If I set in schedule task option "Run with highest privileges" I see in log of my applications such records:
20:12:04.475: EOleException: Метод SaveAs из класса Workbook завершен неверно (SaveAs method of Workbook class finished incorrectly from Russian)
Is there any way to run application with OLE call through Microsort Scheduler?
Or maybe I can work with Excel without OLE (it's pretty simple operations as you could see in my examle)? How can I do it?
The fundamental issue is that Excel needs to run in an interactive desktop. Running through the task scheduler, as you have configured it, runs it in a non-interactive desktop. That's not a supported mode of operation for Excel: http://support.microsoft.com/kb/257757
Your only real hope of success is to create the Excel file without using COM automation of Excel. There are many libraries to help you do that.
Related
During an Inno Setup install I am adding files to a zip archive, see here: Inno Setup Copy Files and Folders to an Existing Zip File. I immediately after adding the files, the archive is renamed by changing the file extension from .zip to .doc.
Code used to rename is:
RenameFile(ExpandConstant('{app}\MyFile.zip'), expandconstant('{app}\MyFile.doc'))
While this used to work well under windows 7 and 8, it has become less reliable and only sometimes works under windows 10.
Note, things I have tried include:
adding sleep(###); intervals but this does not work...
copying the file with a different name as per the accepted answer: Is it possible to move existing directories/files with an INNO script?
Looking for suggestions to make a robust solution and or debugging tips.
[Edit: added the codes... have renamed some bits to make it easier to read]
function SetFileAttributes(lpFileName : String; dwAttribs : LongInt) : Boolean;
external 'SetFileAttributesA#kernel32.dll stdcall';
procedure RepackZip();
var
ResultCode, i: Integer;
x1, x2: string;
begin
// Find files
x1 := FindFile('xmlns="sl:SLA"');
x2 := FindFile('xmlns="sl:SLB"');
log(ExpandConstant('{app}'));
// 2. Copy files to archive
SetFileAttributes ((expandconstant('{app}\MyFile.zip')), 0);
if not FileCopy(ExpandConstant('{tmp}\SLA.xml'), ExpandConstant('{app}\Temp\customXml\') + x1, False) then
MsgBox(x1 + 'failed!', mbError, MB_OK);
if not FileCopy(ExpandConstant('{tmp}\SLB.xml'), ExpandConstant('{app}\Temp\customXml\') + x2, False) then
MsgBox(x2 + 'failed!', mbError, MB_OK);
CopyToArchive();
SetFileAttributes ((expandconstant('{app}\MyFile.zip')), 0);
sleep(100);
// HAVE TRIED COPY & RENAME
// Everything works up to here and both FileCopy and FileRename fail on the same computers (permissions?)
// Have told Inno to Require Admin, makes no difference.
//RenameFile(ExpandConstant('{app}\MyFile.zip'), expandconstant('{app}\MyFile.dotm'))
FileCopy(ExpandConstant('{app}\MyFile.zip'), ExpandConstant('{app}\MyFile.doc'), false);
For i := 0 to 5 do
begin
if not FileExists(ExpandConstant('{app}\MyFile.doc')) then
begin
sleep (250);
end
else begin
// SetFileAttributes ((expandconstant('{app}\MyFile.doc')), 1);
exit;
end;
end;
if not FileExists(expandconstant('{app}\MyFile.doc')) then
MsgBox('Failed - rename archive to .doc', mbError, MB_OK);
end;
And CopyToArchive (this works - but I was wondering if CopyToArchive might somehow be holding the archive open and preventing the rename):
procedure CopyToArchive(); //(const Archive, Content: string);
var
Shell: Variant;
Folder: Variant;
Archive, Content: string;
objFSO, h: Variant;
max0, max1: integer;
begin
Shell := CreateOleObject('Shell.Application');
Archive := ExpandConstant('{app}') + '\MyFile.zip';
Folder := Shell.NameSpace(Archive);
log('Archive Location: ' + Archive);
objFSO := CreateOleObject('Scripting.FileSystemObject');
h := objFSO.getFile(Archive);
Content := ExpandConstant('{app}\Temp\customXml\');
Folder.CopyHere(Content, $0100);
sleep(2000);
end;
One thing that I started looking into was to use objFSO to rename the Archive, but I was unable to figure it out...
There are two problems:
.CopyHere call is asynchronous. After you call it, you have to wait for the archiving to complete. While Sleep is not really realiable, it should do. .CopyHere actually does not lock the file, so it won't prevent the rename, but you may end up renaming an incomplete file.
What causes the rename to fail is your call to objFSO.getFile(Archive), which locks the file and you never unlock it. And you actually never use h. So remove that call.
Why don't you rename the file before archiving? It would prevent all these problems.
I have a question here, I have an application and I need to add images to it. I have tried:
Sheet.Shapes.AddPicture(G_V.Prog_Dir+'pic.BMP',false,true, 190, 10+(15*rowcount), 100, 100 );
it works just fine, but I don't want to give parameters, I want to insert pictures to specified (and parametric) cells because I need to add picture to the last column of the page; this excel needs to be printed I must mention that. So I tried:
Sheet.Range['E'+inttostr(rowcount),'E'+inttostr(rowcount)].Select;
Sheet.Pictures.Insert(G_V.Prog_Dir+'pic.BMP');
It looks OK at first sight, however I think this code links images to the sheet. For example, I send the created Excel to another computer and these images cannot be seen (I don't recall the exact error) and when I searched it, I found out that receiving computer needs to have images at the exact path. As a solution to this, "Sheet.Shapes.AddPicture" recommended but
as I stated before, I need another solution here.
I didn't see anybody experiencing this kind of problem, I hope someone helps me out.
You can use this code to import picture. You do not need exact path if you use AddPicture function with this parameters. it copies photo and paste it to excel.
Set p = ActiveSheet.Shapes.AddPicture(FileName:=PictureFileName,_
linktofile:=msoFalse, savewithdocument:=msoCTrue, _
left:=TargetCell.Left, Top:=TargetCell.Top, Width:=-1,_
Height:=TargetCell.Height)
The simple solution is to add the picture to the clipboard and then paste it into the sheet.
implementation
uses
VCL.Clipbrd, VCL.Graphics, Excel2000;
procedure TForm1.Test;
var
Bitmap: TBitmap;
Excel: TExcelApplication;
Worksheet: TExcelWorksheet;
begin
Bitmap:= TBitmap.Create;
try
Bitmap.LoadFromFile('c:\test.bmp');
Clipboard.Assign(Bitmap);
Excel:= TExcelApplication.Create(self);
Worksheet:= Excel.Worksheets[0];
Worksheet.Range['a1','a1'].Select;
Worksheet.Paste;
finally
Bitmap.Free;
end;
end;
This destroys the previous contents of the clipboard, which is bad form.
You can save/restore the clipboard data using the following routines (based on: https://www.devexpress.com/Support/Center/Question/Details/Q93874)
procedure TForm1.RestoreClipboardData(SourceDataStream: TMemoryStream);
var
AData: THandle;
ADataPtr: Pointer;
begin
if SourceDataStream.Size = 0 then Exit;
Clipboard.Open;
try
AData := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, SourceDataStream.Size);
try
ADataPtr := GlobalLock(AData);
try
SourceDataStream.Position := 0;
SourceDataStream.ReadBuffer(ADataPtr^, SourceDataStream.Size);
SetClipboardData(CF_BITMAP, AData);
finally
GlobalUnlock(AData);
end;
except
GlobalFree(AData);
raise;
end;
finally
Clipboard.Close;
end;
end;
procedure TForm1.SaveClipboardData(DestDataStream: TMemoryStream);
var
AData: THandle;
ADataPtr: Pointer;
begin
if DestDataStream = nil then raise Exception.Create('Dest is nil');
Clipboard.Open;
try
AData := GetClipboardData(CF_BITMAP);
if AData = 0 then Exit;
ADataPtr := GlobalLock(AData);
try
DestDataStream.Size := GlobalSize(AData);
DestDataStream.Position := 0;
DestDataStream.Write(ADataPtr^, DestDataStream.Size);
finally
GlobalUnlock(AData);
end;
finally
Clipboard.Close;
end;
end;
Good day people. First off, I'm not an native English speaker I might have some grammar mistakes or such.
I need an advice from people who has done something or an application alike mine, well, the thing is that I'm using a TProgressBar in my delphi form, another component called "TExcelApplication" and a TDBGrid.
When I export the DBGrid's content, the application "freezes", so I basically put that ProgressBar for the user to see how much the process is completed. I've realized that when the TDBGrid is retrieving and exporting each row to the new Excel workbook, you can't move the actual form, so you have to wait until the process is completed to move that form.
So, is it possible to do something (I thought about threads but I'm not sure if they could help) so the user could move the window if he wanted?
Thank you so much for taking your time in reading and giving me an advice. I'm using Delphi XE.
Here's the code I use to export the rows:
with ZQDetalles do
begin
First;
while not EOF do
begin
i := i + 1;
workSheet.Cells.Item[i,2] := DBGridDetalles.Fields[0].AsString;
workSheet.Cells.Item[i,3] := DBGridDetalles.Fields[1].AsString;
workSheet.Cells.Item[i,4] := DBGridDetalles.Fields[2].AsString;
workSheet.Cells.Item[i,5] := DBGridDetalles.Fields[3].AsString;
workSheet.Cells.Item[i,6] := DBGridDetalles.Fields[4].AsString;
workSheet.Cells.Item[i,7] := DBGridDetalles.Fields[5].AsString;
workSheet.Cells.Item[i,8] := DBGridDetalles.Fields[6].AsString;
workSheet.Cells.Item[i,9] := DBGridDetalles.Fields[7].AsString;
Next;
barraProgreso.StepIt;
end;
end;
If you want to see the whole code for the "Export" button, then feel free to see this link: http://pastebin.com/FFWAPdey
Whenever you're doing stuff that takes a significant amount of time in an application with GUI you want to put it in a seperate thread so the user can still operate the form. You can declare a simple thread as such:
TWorkingThread = class(TThread)
protected
procedure Execute; override;
procedure UpdateGui;
procedure TerminateNotify(Sender: TObject);
end;
procedure TWorkingThread.Execute;
begin
// do whatever you want to do
// make sure to use synchronize whenever you want to update gui:
Synchronize(UpdateGui);
end;
procedure TWorkingThread.UpdateGui;
begin
// e.g. updating the progress bar
end;
procedure TWorkingThread.TerminateNotify(Sender: TObject);
begin
// this gets executed when the work is done
// usually you want to give some kind of feedback to the user
end;
// ...
// calling the thread:
procedure TSettingsForm.Button1Click(Sender: TObject);
var WorkingThread: TWorkingThread;
begin
WorkingThread := TWorkingThread.Create(true);
WorkingThread.OnTerminate := TerminateNotify;
WorkingThread.FreeOnTerminate := true;
WorkingThread.Start;
end;
It's pretty straight forward, remember to always use Synchronize when you want to update visual elements from a thread. Usually, you also want to take care that the user can't invoke the thread again while it's still doing work as he's now able to use the GUI.
If the number of rows is small (and you know how many you'll have), you can transfer the data much more quickly (and all at once) using a variant array of variants, something like this:
var
xls, wb, Range: OLEVariant;
arrData: Variant;
RowCount, ColCount, i, j: Integer;
Bookmark: TBookmark;
begin
// Create variant array where we'll copy our data
// Note that getting RowCount can be slow on large datasets; if
// that's the case, it's better to do a separate query first to
// ask for COUNT(*) of rows matching your WHERE clause, and use
// that instead; then run the query that returns the actual rows,
// and use them in the loop itself
RowCount := DataSet1.RecordCount;
ColCount := DataSet1.FieldCount;
arrData := VarArrayCreate([1, RowCount, 1, ColCount], varVariant);
// Disconnect from visual controls
DataSet1.DisableControls;
try
// Save starting row so we can come back to it after
Bookmark := DataSet1.GetBookmark;
try
{fill array}
i := 1;
while not DataSet1.Eof do
begin
for j := 1 to ColCount do
arrData[i, j] := DataSet1.Fields[j-1, i-1].Value;
DataSet1.Next;
Inc(i);
// If we have a lot of rows, we can allow the UI to
// refresh every so often (here every 100 rows)
if (i mod 100) = 0 then
Application.ProcessMessages;
end;
finally
// Reset record pointer to start, and clean up
DataSet1.GotoBookmark;
DataSet1.FreeBookmark;
finally
// Reconnect GUI controls
DataSet1.EnableControls;
end;
// Initialize an instance of Excel - if you have one
// already, of course the next couple of lines aren't
// needed
xls := CreateOLEObject('Excel.Application');
// Create workbook - again, not needed if you have it.
// Just use ActiveWorkbook instead
wb := xls.Workbooks.Add;
// Retrieve the range where data must be placed. Again, your
// own WorkSheet and start of range instead of using 1,1 when
// needed.
Range := wb.WorkSheets[1].Range[wb.WorkSheets[1].Cells[1, 1],
wb.WorkSheets[1].Cells[RowCount, ColCount]];
// Copy data from allocated variant array to Excel in single shot
Range.Value := arrData;
// Show Excel with our data}
xls.Visible := True;
end;
It still takes the same amount of time to loop through the rows and columns of the data, but the time taken to actually transfer that data to Excel is drastically reduced, particularly if there's a good amount of data.
I am using Delphi 7 to generate CSV file from data acquired from COM port. Now, this seems to work OK since any other spreadsheet software reads generated file properly (Open Office and Libre Office spreadshhet software, for instance). Excel 2007 does the following. Instead of these two column values:
1.976139e-2<TAB>22.98027
i got these two column values:
1.98E+04<TAB>2.298.027
Note that generated file opened in any text editor (Notepad++ for instance) has proper values.
What could be the problem here ?
Thanks,
Josip
If the setting in Delphi do not fit your needs you could change them before loading the CSV. But you should make sure to reset them afterwards.
var
Excel, WorkBook: Variant;
KeepDecimalSeparator, KeepThousandsSeparator: String;
KeepUseSystem: Boolean;
begin
Excel := CreateOleObject('Excel.Application');
Excel.Visible := true;
try
KeepDecimalSeparator := Excel.DecimalSeparator;
KeepThousandsSeparator := Excel.ThousandsSeparator;
KeepUseSystem := Excel.UseSystemSeparators;
Excel.DecimalSeparator := '.';
Excel.ThousandsSeparator := ',';
Excel.UseSystemSeparators := false;
WorkBook := Excel.WorkBooks.Open('C:\Temp\1.csv');
finally
Excel.DecimalSeparator := KeepDecimalSeparator;
Excel.ThousandsSeparator := KeepThousandsSeparator;
Excel.UseSystemSeparators := KeepUseSystem;
end;
end;
Try to use quotes.
"1.976139e-2"<TAB>"22.98027"
I wrote a Delphi program that extracts and consolidates data from several different spreadsheets of a single .XLS file, to a text file for later processing. It is a Delphi 7 console program.
An excerpt of the most relevant pieces of code will show you that, apparently, my program is pretty well behaved or at least as much as it needs to be.
uses ... ActiveX, ComObj ... ;
procedure Fatal(s:string);
...
Halt(1);
var ExcelApp:Variant; (* global var *)
begin (* main program block *)
coInitialize(nil);
ExcelApp:=CreateOleObject('Excel.Application');
try
ExcelApp.Visible:=False;
ExcelApp.WorkBooks.Open(ExcelFileName);
...
XLSSheet := ExcelApp.Worksheets[ExcelSheetName];
...
try
XLSRange := XLSSheet.Range[ExcelRangeName];
except
Fatal('Range "'+ExcelRangeName+'" not found');
end;
if VarIsNull(XLSRange) then Fatal('Range '+ExcelRangeName+' not found');
for row:=XLSRange.Row to XLSRange.Rows[XLSRange.Rows.Count].Row do
for col:=XLSRange.Column to XLSRange.Columns[XLSRange.Columns.Count].Column do
CellValue:=XLSSheet.Cells[Row,Col].Value;
...
if CellValue<>'' then ...
...
ExcelApp.Workbooks.Close;
...
finally
ExcelApp.Quit;
coUninitialize;
end;
end.
Sometimes, when the program exits, the XLS remains locked. Looking at the Task Manager, I see that Excel.exe process that was started when the client program ran, is still running, eventhoug the client program has exited and succesfully unloaded.
Do you happen to know what are the usual suspects for this behaviour? have any idea where to look for always unloading excel upon client execution?
You need to release the ExcelApp variant. It still holds a reference count of 1, and therefore Excel isn't completely closed.
Add this to your code (the marked line):
finally
ExcelApp.Quit;
ExcelApp := Unassigned; // Add this line
coUninitialize;
end;
Here is some simple code to reproduce the problem, and test the solution:
// Add two buttons to a form, and declare a private form field.
// Add OnClick handlers to the two buttons, and use the code provided.
// Run the app, and click Button1. Wait until Excel is shown, and then click
// Button2 to close it. See the comments in the Button2Click event handler.
type
TForm1=class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
ExcelApp: Variant;
end;
implementation
uses
ComObj;
procedure TForm1.Button1Click(Sender: TObject);
begin
ExcelApp := CreateOleObject('Excel.Application');
ExcelApp.Visible := True;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
ExcelApp.Visible := False;
ExcelApp.Quit;
// Leave the next line commented, run the app, and click the button.
// After exiting your app NORMALLY, check Task Manager processes, and you'll
// see an instance of Excel.exe still running, even though it's not
// in the Applications tab.
//
// Do an "end process" in Task Manager to remove the orphaned instance
// of Excel.exe left from the above. Uncomment the next line of code
// and repeat the process, again closing your app normally after clicking
// Button2. You'll note that Excel.exe is no longer in
// Task Manager Processes after closing your app.
// ExcelApp := Unassigned;
end;
end.
I have encountered much the same problem in XE2 and my solution was to replace such code samples:
fExcel.ActiveWorkBook.ActiveSheet.Range[
fExcel.ActiveWorkBook.ActiveSheet.Cells[3, 2],
fExcel.ActiveWorkBook.ActiveSheet.Cells[3+i,1+XL_PT_Tip_FieldCount]
].Formula := VarArr;
with:
cl := fExcel.ActiveWorkBook.ActiveSheet.Cells[3, 2];
ch := fExcel.ActiveWorkBook.ActiveSheet.Cells[3+i,1+XL_PT_Tip_FieldCount];
fExcel.ActiveWorkBook.ActiveSheet.Range[cl, ch].Formula := VarArr;
Same happens in this case, where sheet variable is used:
sheetDynamicHb := fExcel.ActiveWorkBook.Sheets['Dynamics Hb'];
cl := sheetDynamicHb.Cells[52, 2];
ch := sheetDynamicHb.Cells[52+i, 2+3];
sheetDynamicHb.Range[cl, ch].Formula := VarArr;
Somehow introducing temp variables (cl,ch: Variant) does the trick. It seems like the nested Excel variable access does something odd. I can not explain why this works like that, but it does work..
I faced the same issue trying to close "zombie" Excel processes (the ones that stay running if I launch them from my app and then forced terminate the app). I tried all suggested actions with no luck. Finally I created a combined killer procedure that robustly does the trick using WinApi if usual COM methods do not help.
procedure KillExcel(var App: Variant);
var
ProcID: DWORD;
hProc: THandle;
hW: HWND;
begin
hW := App.Application.Hwnd;
// close with usual methods
App.DisplayAlerts := False;
App.Workbooks.Close;
App.Quit;
App := Unassigned;
// close with WinApi
if not IsWindow(hW) then Exit; // already closed?
GetWindowThreadProcessId(hW, ProcID);
hProc := OpenProcess(PROCESS_TERMINATE, False, ProcID);
TerminateProcess(hProc, 0);
end;