Convert XLSX to PDF on one page by Spire.Pdf (c#) - c#

I have one page XLSX work sheet (invoice). I need to convert it to one page PDF document. For it I am using Spire library. But it covert my document to two pages.
Code:
using (ExcelPackage xlPackageRef = new ExcelPackage(totalXlsFile))
{
using (ExcelPackage xlPackage = new ExcelPackage(workXlsFile))
{
ExcelWorkbook wb = xlPackage.Workbook;
ExcelWorkbook wbRef = xlPackageRef.Workbook;
var sheetName = invoice.XlsSeznamFakturNazevListu;
OfficeOpenXml.ExcelWorksheet wsRef = wbRef.Worksheets[sheetName];
if (wsRef != null)
{
// create xls work file
wb.Worksheets.Add("faktura", wsRef);
xlPackage.Save();
// load Excel file
Workbook workbook = new Workbook();
workbook.LoadFromFile(workXlsFilePath);
// pdf file path
FileInfo pdfInvoiceFile = new FileInfo(pdfInvoiceTargetFolder + #"/" + pdfInvoiceFileName);
if (pdfInvoiceFile.Exists)
pdfInvoiceFile.Delete();
// create pdf file
workbook.SaveToFile(pdfInvoiceFile.FullName, Spire.Xls.FileFormat.PDF);
}
}
}

First, I suppose you were using Spire.XLS rather than Spire.PDF.
Second, you need to do some page setup before converting. Try below code:
Worksheet worksheet = workbook.Worksheets[index];
PageSetup setup = worksheet.PageSetup;
setup.FitToPagesWide = 1;
setup.FitToPagesTall = 1;

Related

Closedxml - get the link to an already open Excel workbook

I have a project VSTO EXCEL. I would like to work with ClosedXML library, but can`t get the link on the open ActiveSheet. My code:
private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
var workbook = **?**;
var ws = workbook.Worksheet(1);
var rngHeaders = ws.Range("B3:F3");
rngHeaders.Style.Fill.BackgroundColor = XLColor.LightSalmon;
}
This example does`t work:
var workbook = ThisApplication.ThisWorkbook;
I know there is this way:
using (var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.SaveAs("HelloWorld.xlsx");
}
But I have to work with already opened Workbook.
To open an Excel file with ClosedXML, you have to open a saved file (by filename) or a filestream. You can't open a workbook which is already opened in Excel or another application.

Copying sheet to another Excel workbook using C# and OpenXML

Sheet 2 contains the lists which are created previously, and sheet 1 contains the links to sheet 2, so when I generate sheet 1, I want sheet 2 to be copied to the workbook.
static void CopySheet(string filename, string sheetName, string clonedSheetName) {
//Add new sheet to main workbook part
Sheets sheets = workbookPart.Workbook.GetFirstChild<Sheets>();
Sheet copiedSheet = new Sheet();
copiedSheet.Name = clonedSheetName;
copiedSheet.Id = workbookPart.GetIdOfPart(clonedSheet);
copiedSheet.SheetId = (uint)sheets.ChildElements.Count + 1;
sheets.Append(copiedSheet);
//Save Changes
workbookPart.Workbook.Save();
}
Try
using (ExcelPackage ExcelFile = new ExcelPackage(new System.IO.FileInfo(#"C:\temp\MyExcelFile.xlsx")))
{
ExcelFile.Workbook.Worksheets.Copy("SheetToCopyName", "SheetToCopyToName");
}
This is done with EPPlus which uses OpenXML library. If you're using another library let me know.

ExcelPackage not Saving programmatically using C#

I'm trying to edit an existing excel file with .xlsx extension using C#,but it is not saving the new value.My code is as follows.Can anybody help me?
string path = #"D:\Demo\test.xlsx" ;
FileInfo file = new FileInfo(Path.GetFileName(path));
using (ExcelPackage xlPackage = new ExcelPackage(file))
{
ExcelWorkbook workBook = xlPackage.Workbook;
ExcelWorksheet ws = workBook.Worksheets[1];
ws.Cells[8, 6].Value = 25;
xlPackage.Save();
}
Put the # symbol before your path string to prevent automatic stripping or manually escape your \ characters
string path = #"D:\test\test.xslx";
Or
string path = "D:\\test\\test.xslx";

The process cannot access the file because it is being used by another process using spreadsheet document

Please help me to solve the problem, when i save the excel file throw this error i convert the excel file to zip file.
zip.Save(#"" + root + "/" + "" + userid + ".zip");
the process cannot access the file because it is being used by another process
my code is below
using (SpreadsheetDocument document = SpreadsheetDocument.Create(excelFilename, SpreadsheetDocumentType.Workbook))
{
WriteExcelFile(ds, document);
}
private static void WriteExcelFile(DataSet ds, SpreadsheetDocument spreadsheet)
{
spreadsheet.AddWorkbookPart();
spreadsheet.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
spreadsheet.WorkbookPart.Workbook.Append(new BookViews(new WorkbookView()));
// If we don't add a "WorkbookStylesPart", OLEDB will refuse to connect to this .xlsx file !
WorkbookStylesPart workbookStylesPart = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>("rIdStyles");
Stylesheet stylesheet = new Stylesheet();
workbookStylesPart.Stylesheet = stylesheet;
// Loop through each of the DataTables in our DataSet, and create a new Excel Worksheet for each.
uint worksheetNumber = 1;
foreach (DataTable dt in ds.Tables)
{
// For each worksheet you want to create
string workSheetID = "rId" + worksheetNumber.ToString();
string worksheetName = dt.TableName;
WorksheetPart newWorksheetPart = spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet();
// create sheet data
newWorksheetPart.Worksheet.AppendChild(new DocumentFormat.OpenXml.Spreadsheet.SheetData());
// save worksheet
WriteDataTableToExcelWorksheet(dt, newWorksheetPart);
newWorksheetPart.Worksheet.Save();
// create the worksheet to workbook relation
if (worksheetNumber == 1)
spreadsheet.WorkbookPart.Workbook.AppendChild(new DocumentFormat.OpenXml.Spreadsheet.Sheets());
spreadsheet.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>().AppendChild(new DocumentFormat.OpenXml.Spreadsheet.Sheet()
{
Id = spreadsheet.WorkbookPart.GetIdOfPart(newWorksheetPart),
SheetId = (uint)worksheetNumber,
Name = dt.TableName
});
worksheetNumber++;
}
spreadsheet.WorkbookPart.Workbook.Save();
}
I see that you have saved your document but you have not closed it. So, it will still be open with the spreadsheetdocument object.
Add the following line after you save the document.
spreadsheet.WorkbookPart.Workbook.Close();
If it doesn't help, kindly provide the full code so that we can look into it further. Good luck.
I think you are not closing all your Workbooks before you try to put them in the Zip-File.
Put this at the end of the Method:
private static void WriteExcelFile(DataSet ds, SpreadsheetDocument spreadsheet)
{
...
spreadsheet.WorkbookPart.Workbook.Close();
}

Copy specific worksheets to new Excel file

I have an Excel file.
I need to open it, select specific sheets from it, and convert those sheets to a PDF format. I am able to convert the whole excel file, I just don't know how to convert only the specific sheets.
My idea is to copy specific sheets from an existing file to a new temporary file, and convert that whole new temporary file to PDF.
Maybe there's an easier way?
My code so far is =>
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
public static void ExportExcel(string infile, string outfile, int[] worksheets)
{
Excel.Application excelApp = null;
Excel.Application newExcelApp = null;
try
{
excelApp = new Excel.Application();
excelApp.Workbooks.Open(infile);
//((Microsoft.Office.Interop.Excel._Worksheet)excelApp.ActiveSheet).PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;
excelApp.ActiveWorkbook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, outfile);
}
finally
{
if (excelApp != null)
{
excelApp.DisplayAlerts = false;
excelApp.SaveWorkspace();
excelApp.Quit();
}
}
}
Maybe the ExportAsFixedFormat method can be set to consider only specific pages (sheets) while converting?
If not, how do I copy the sheets from one file to another?
Thanks!
You might be able to just print the sheets you want from the original file. I fired up the Macro Recorder, selected a couple of sheets, and Saved As to PDF. Here's the code:
Sheets(Array("Sheet1", "Sheet2")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\doug\Documents\Book1.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
When I changed the selected sheets and ran again it worked as expected.
What's strange is that in the actual Save As dialog, you can go to Options and check "Selected Sheets." That's not available as a parameter to ExportAsFixedFormat, but it was automatically selected in the dialog, and maybe is the default also when called.
You could simply copy the file to the new destination, open the destination, remove the unwanted sheets and export. This is an example (tested) of my idea.
// infile is the excel file, outfile is the pdf to build, sheetToExport is the name of the sheet
public static void ExportExcel(string infile, string outfile, string sheetToExport)
{
Microsoft.Office.Interop.Excel.Application excelApp = new
Microsoft.Office.Interop.Excel.Application();
try
{
string tempFile = Path.ChangeExtension(outfile, "XLS");
File.Copy(infile, tempFile, true);
Microsoft.Office.Interop.Excel._Workbook excelWorkbook =
excelApp.Workbooks.Open(tempFile);
for(int x = excelApp.Sheets.Count; x > 0; x--)
{
_Worksheet sheet = (_Worksheet)excelApp.Sheets[x];
if(sheet != null && sheet.Name != sheetToExport)
sheet.Delete();
}
excelApp.ActiveWorkbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, outfile);
}
finally
{
if (excelApp != null)
{
excelApp.DisplayAlerts = false;
excelApp.SaveWorkspace();
excelApp.Quit();
}
}
}

Categories