Skip to content

Excel multi sheet #239

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
218 changes: 183 additions & 35 deletions src/ExcelUtils.pas
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,20 @@
****************************************************************)
interface

uses Classes,Sysutils, MainUtils, ResourceUtils, ActiveX, ComObj, WinINet, Variants, Excel_TLB_Constants,StrUtils;
uses Classes,Sysutils, MainUtils, ResourceUtils, ActiveX, ComObj, WinINet, Variants,

Excel_TLB_Constants,StrUtils;

type

TExcelXLSConverter = Class(TDocumentConverter)
Private
ExcelApp : OleVariant;
FExcelVersion : String;
function SingleFileExecuteConversion(fileToConvert, OutputFilename: String; OutputFileFormat: Integer): TConversionInfo;
procedure SaveAsPDF(OutputFilename : string) ;
procedure SaveAsXPS(OutputFilename: string);
procedure SaveAsCSV(OutputFilename: string);

public
constructor Create() ;
Expand Down Expand Up @@ -88,7 +94,10 @@ function TExcelXLSConverter.ExecuteConversion(fileToConvert: String; OutputFilen
var
NonsensePassword :OleVariant;
FromPage, ToPage : OleVariant;
activeSheet : OleVariant;
dynamicoutputDir, dynamicoutputFile, dynamicoutputExt, dynamicOutputFileName, dynamicSheetName : String;
ExitAction :TExitAction;
Sheet : integer;
begin
//Excel is particuarily sensitive to having \\ at end of filename, eg it won't create file.
//so we remove any double \\
Expand All @@ -98,6 +107,7 @@ function TExcelXLSConverter.ExecuteConversion(fileToConvert: String; OutputFilen
Result.InputFile := fileToConvert;
Result.Successful := false;
NonsensePassword := 'tfm554!ghAGWRDD';
LogDebug('in conversion file');
try
ExcelApp.Workbooks.Open( FileToConvert, //FileName ,
EmptyParam, //UpdateLinks ,
Expand Down Expand Up @@ -155,52 +165,53 @@ function TExcelXLSConverter.ExecuteConversion(fileToConvert: String; OutputFilen
aSave: // Go ahead and save
begin

Result := SingleFileExecuteConversion(fileToConvert, OutputFilename, OutputFileFormat);
end;
end;

//Unlike Word, in Excel you must call a different function to save a pdf and XPS.
if OutputFileFormat = xlTypePDF then
begin

if pdfPrintToPage > 0 then
begin
logdebug('PrintFromPage: ' + inttostr(pdfPrintFromPage),debug);
logdebug('PrintToPage: ' + inttostr(pdfPrintToPage),debug);
end;

FromPage := pdfPrintFromPage;
ToPage := pdfPrintToPage;

end else
begin
FromPage := EmptyParam;
ToPage := EmptyParam;
end ;
//Useful Links:
// https://docs.microsoft.com/en-us/office/vba/api/excel.workbooks.open
// https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.exportasfixedformat

ExcelApp.Application.DisplayAlerts := False ;
ExcelApp.activeWorkbook.ExportAsFixedFormat(XlFixedFormatType_xlTypePDF,
OutputFilename,
EmptyParam, //Quality
IncludeDocProps, // IncludeDocProperties,
False,// IgnorePrintAreas,
FromPage , // From,
ToPage, // To,
pdfOpenAfterExport, // OpenAfterPublish, (default false);
EmptyParam// FixedFormatExtClassPtr
) ;
function TExcelXLSConverter.SingleFileExecuteConversion(fileToConvert: String; OutputFilename: String; OutputFileFormat : Integer): TConversionInfo;
var
NonsensePassword :OleVariant;
FromPage, ToPage : OleVariant;
activeSheet : OleVariant;
dynamicoutputDir, dynamicoutputFile, dynamicoutputExt, dynamicOutputFileName, dynamicSheetName : String;
ExitAction :TExitAction;
Sheet : integer;
begin

ExcelApp.ActiveWorkBook.Saved := True
logdebug('SingleFileExecuteConversion',VERBOSE);

//Unlike Word, in Excel you must call a different function to save a pdf and XPS.
if OutputFileFormat = xlTypePDF then
begin

SaveAsPDF(OutputFilename);


end
else if OutputFileFormat = xlTypeXPS then
begin
ExcelApp.Application.DisplayAlerts := False ;
ExcelApp.activeWorkbook.ExportAsFixedFormat(XlFixedFormatType_xlTypeXPS, OutputFilename );
ExcelApp.ActiveWorkBook.save;
SaveAsXPS(OutputFilename);
end
else if OutputFileFormat = xlCSV then
begin
//CSV pops up alert. must be hidden for automation
ExcelApp.Application.DisplayAlerts := False ;
ExcelApp.activeWorkbook.SaveAs( OutputFilename, OutputFileFormat);



// to get sheets
// Sheets(Array("Sheet4", "Sheet5")) or Sheets(3) or Sheets(Array(1,2))



ExcelApp.activeWorkbook.SaveAs( OutputFilename, OutputFileFormat);
ExcelApp.ActiveWorkBook.saved := true;
end
else
Expand All @@ -217,8 +228,6 @@ function TExcelXLSConverter.ExecuteConversion(fileToConvert: String; OutputFilen
Result.OutputFile := OutputFilename;
ExcelApp.ActiveWorkbook.Close();

end;
end;
end;


Expand All @@ -244,4 +253,143 @@ function TExcelXLSConverter.OfficeAppVersion(): String;
result := FExcelVersion;
end;


procedure TExcelXLSConverter.SaveAsPDF(OutputFilename : string) ;
var

FromPage, ToPage, SheetList, ExcelSheets : OleVariant;
Sheet1,Sheet2,Sheet3 , Workbook , SheetsArray: OleVariant;
activeSheet : OleVariant;

begin
ExcelApp.Application.DisplayAlerts := False ;

if pdfPrintToPage > 0 then
begin
logdebug('PrintFromPage: ' + inttostr(pdfPrintFromPage),debug);
logdebug('PrintToPage: ' + inttostr(pdfPrintToPage),debug);

FromPage := pdfPrintFromPage;
ToPage := pdfPrintToPage;

end else
begin
FromPage := EmptyParam;
ToPage := EmptyParam;
end ;
(*
Sheets(Array("Wednesday Lunch", "Sheet2", "Sheet3")).Select
Sheets("Wednesday Lunch").Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Development\github\docto\test\GeneratedTestputFiles\wk1test-MultiShasdfasdfeetmulti635345.pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
ActiveCell.FormulaR1C1 = ""
Range("AM13").Select
End Sub*)

if SelectedSheets.Count = 0 then
begin
logDebug('Selecting sheets',VERBOSE);
SheetList := VarArrayCreate([0, 2], varVariant); // 3 sheets
SheetList[0] := 'Wednesday Lunch';
SheetList[1] := 'Sheet2';
SheetList[2] := 'Sheet3';

Workbook := ExcelApp.activeWorkbook;
// Get references to the individual sheets
// Sheet1 := Workbook.Worksheets[3];
// Sheet2 := Workbook.Worksheets[2] ;
// Sheet3 := Workbook.Worksheets[1];

// Create a variant array of the sheet COM objects
SheetsArray := VarArrayCreate([0, 1], varVariant);
SheetsArray[0] := 2;
SheetsArray[1] := 3;
// SheetsArray[2] := 3;

// Select the sheets
// ExcelApp.activeWorkbook.worksheets(SheetsArray).Select;

// ExcelApp.activeWorkbook.worksheets.Select(3);
//ExcelApp.activeWorkbook.Sheets.Item[2] .Select;

activeSheet := ExcelApp.ActiveWorkbook.Sheets.Item[3];

logDebug('SeT sheets',VERBOSE);
ExcelApp.ActiveWorkBook.save;
end ;




ExcelApp.Application.DisplayAlerts := False ;
activeSheet.ExportAsFixedFormat(XlFixedFormatType_xlTypePDF,
OutputFilename,
EmptyParam, // Quality
IncludeDocProps, // IncludeDocProperties,
False, // IgnorePrintAreas,
FromPage , // From,
ToPage, // To,
pdfOpenAfterExport, // OpenAfterPublish, (default false);
EmptyParam // FixedFormatExtClassPtr
) ;






ExcelApp.ActiveWorkBook.Saved := True

end;


procedure TExcelXLSConverter.SaveAsXPS(OutputFilename : string) ;
begin

ExcelApp.Application.DisplayAlerts := False ;
ExcelApp.activeWorkbook.ExportAsFixedFormat(XlFixedFormatType_xlTypeXPS, OutputFilename );
ExcelApp.ActiveWorkBook.save;
end;

procedure TExcelXLSConverter.SaveAsCSV(OutputFilename: string);
var
FromPage, ToPage : OleVariant;
activeSheet : OleVariant;
dynamicoutputDir, dynamicoutputFile, dynamicoutputExt, dynamicOutputFileName, dynamicSheetName : String;
ExitAction :TExitAction;
Sheet : integer;
begin
LogDebug('output to csv format');

//CSV pops up alert. must be hidden for automation
ExcelApp.Application.DisplayAlerts := False ;

// if fSelectedSheets.Count > 0 then


dynamicoutputDir := ExtractFilePath(OutputFilename); // includes last \
dynamicoutputFile := ChangefileExt ( ExtractFileName(OutputFilename),'');
dynamicoutputExt := ExtractFileExt(OutputFilename);

for Sheet := 1 to ExcelApp.ActiveWorkbook.WorkSheets.Count do
begin
activeSheet := ExcelApp.ActiveWorkbook.Sheets[Sheet];
dynamicSheetName := activeSheet.Name;

LogDebug(dynamicSheetName);

dynamicSheetName := SafeFileName(dynamicSheetName);
dynamicOutputFilename := dynamicoutputDir + dynamicoutputFile + '_(' + inttostr(Sheet) + dynamicSheetName + ')' + dynamicoutputExt;

LogDebug(dynamicOutputFileName);

activeSheet.SaveAs( dynamicoutputFilename, OutputFileFormat);
end;


ExcelApp.ActiveWorkBook.save;
end;

end.
Binary file modified src/ExtraFiles.res
Binary file not shown.
26 changes: 23 additions & 3 deletions src/MainUtils.pas
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ interface

Const
VERBOSE = 10;
DEBUG = 9;
DEBUG = 9;
HELP = 8;
CHATTY = 5;
STANDARD = 2;
Expand All @@ -33,8 +33,8 @@ interface
MSVISIO = 4;


DOCTO_VERSION = '1.15.45'; // dont use 0x - choco needs incrementing versions.
DOCTO_VERSION_NOTE = ' x64 Release ';
DOCTO_VERSION = '2.0.42'; // dont use 0x - choco needs incrementing versions.
DOCTO_VERSION_NOTE = ' (Test Version XLS Multisheet B) ';
type


Expand Down Expand Up @@ -71,6 +71,7 @@ TDocumentConverter = class
FKeepIRM: boolean;
FDocStructureTags: boolean;
FBitmapMissingFonts: boolean;
fSelectedSheets: TStrings;


procedure SetCompatibilityMode(const Value: Integer);
Expand All @@ -95,6 +96,7 @@ TDocumentConverter = class
procedure SetKeepIRM(const Value: boolean);
procedure SetDocStructureTags(const Value: boolean);
procedure SetBitmapMissingFonts(const Value: boolean);
procedure Setsheets(const Value: TStrings);


protected
Expand Down Expand Up @@ -184,6 +186,8 @@ TDocumentConverter = class
property pdfPrintToPage : integer read FpdfPrintToPage;
property useISO190051 : boolean read FuseISO190051;
property pdfOptimizeFor : integer read fpdfOptimizeFor write fpdfOptimizeFor;
property SelectedSheets : TStrings read fSelectedSheets write Setsheets;


property ExportMarkup : integer read fExportMarkup;
property IncludeDocProps : boolean read FIncludeDocProps write SetIncludeDocProps;
Expand Down Expand Up @@ -217,6 +221,7 @@ TDocumentConverter = class
// Check Should Ignore
function CheckShouldIgnore(DocumentPath : String): Boolean;

function SafeFileName(FileName: String ) : String;

public

Expand Down Expand Up @@ -518,6 +523,7 @@ constructor TDocumentConverter.Create;
FBitmapMissingFonts := true;
FInputFiles := TStringList.Create;
fDontUseAutoVBA := true;
fSelectedSheets := TStringList.Create;


end;
Expand All @@ -539,6 +545,7 @@ destructor TDocumentConverter.Destroy;


FInputFiles.Free;
fSelectedSheets.Free;

if assigned(FNetHandle) then
begin
Expand Down Expand Up @@ -1642,6 +1649,14 @@ procedure TDocumentConverter.WriteOfficeAppVersion(Version: String);
LogDebug('Writing Version to File:' + ConfigFileName,VERBOSE);
end;

function TDocumentConverter.SafeFileName(FileName: String): String;
begin
Filename := StringReplace(Filename,'&','_',[rfReplaceAll,rfIgnoreCase]);
Filename := StringReplace(Filename,'/','_',[rfReplaceAll,rfIgnoreCase]);
Filename := StringReplace(Filename,'\\','_',[rfReplaceAll,rfIgnoreCase]);
result := Filename;
end;

procedure TDocumentConverter.SetBitmapMissingFonts(const Value: boolean);
begin
FBitmapMissingFonts := Value;
Expand Down Expand Up @@ -1851,6 +1866,11 @@ procedure TDocumentConverter.SetRemoveFileOnConvert(const Value: boolean);



procedure TDocumentConverter.Setsheets(const Value: TStrings);
begin
fSelectedSheets := Value;
end;

procedure TDocumentConverter.SetSkipDocsWithTOC(const Value: Boolean);
begin
FSkipDocsWithTOC := Value;
Expand Down
7 changes: 6 additions & 1 deletion src/res/HelpLog.txt
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,15 @@ Long Parameters:
--PDF-no-BitmapMissingFonts
Do not bitmap missing fonts, fonts will be substituted.
--use-ISO190051
Create PDF to the ISO 19005-1 standard.
Create PDF to the ISO 19005-1 standard.

--enable-wordvbaauto
By Default any autorun vba will not run, use this parameter if you wish vba to Autorun. Word Only.

--sheets
Select which sheets to save. Can be comma seperated list of 0 index numbers or sheet names. Excel Only.
--allsheets
If converting to CSV default behaviour is to convert first sheet. This will convert all with appropriate names


Experimental:
Expand Down
Binary file modified test/inputfilesxl/Week 1 Test.xls
Binary file not shown.
Binary file added test/inputfilesxl/wk1test-MultiSheet.xls
Binary file not shown.
Binary file added test/inputfilesxl/wk1test.xls
Binary file not shown.
2 changes: 1 addition & 1 deletion test/testxlsfile.bat
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
REM Load csv files convert to xls
"../exe/32/docto.exe" -XL -f "C:\dev\github\docto\test\inputfilesxl\Week 1 Test.xls" -o "C:\dev\github\docto\test\GeneratedFiles" -T xlPDF -l 10
"../exe/32/docto.exe" -XL -f "C:\dev\github\docto\test\inputfilesxl\Week 1 Test.xls" -o "C:\dev\github\docto\test\GeneratedFiles" -T xlPDF -l 10