Saving Excel as PDF fitting everything into one page not working - c#

As part of the project, I need to save some range of Excel cells as a PDF file, still making everything fit in one page. If there are more data than fit to one page, it needs to be nicely trimmed and go to the 2nd page.
My code saves an Excel file as PDF, but there are 8 pages now, and the data are displayed big and there is a lot of blank spaces around each edge of the page.
Also, not all columns are fit in one page. It is like the first page has column A through column G, and later in other pages, I see column H through column M, but this is not what I want.
var excelPath = "My Excel file path.xlsx"; //Excel file path
var pdfPath = "My PDf file path.pdf"; //Pdf file path
var sheetName = "25. Data"; //Excel sheet name to get data from
var printRange = "A1:M70"; //Area that needs to be included in PDF
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
var wb = app.Workbooks.Open(excelPath);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[sheetName];
ws.PageSetup.Orientation = xlPageOrientation.xlLandscape;
ws.PageSetup.PrintArea = printRange;
ws.PageSetup.FitToPagesWide = 1;
ws.PageSetup.FitToPagesTall = false;
wb.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, pdfPath);
Can someone tell me what is wrong with this code??

Figured it out. I didn't know why but PageSetup.Zoom was set to 100 by default. Adding
ws.PageSetup.Zoom = false;
fixed the issue. Microsoft page says if this value is set to true, FitToPagesTall and FitToPagesWide will be ignored.

Related

EPPlus InsertRow corrupts excel file

I am currently comparing different files with each other and put the output in an Excel Workbook with multiple worksheets (one per file comparison) using EPPlus 4.5.3.3.
The worksheets are simple ranges - no tables.
Sometimes it is required to move the content of one Excel Sheet to a certain row in another Excel Sheet.
For this I am using the InsertRow function of EPPlus. The function itself does the trick and inserts the content at the desired row.
However, when opening the Workbook I receive these errors:
The content of that XML file is the following:
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<logFileName>error044200_02.xml</logFileName>
<summary>Errors were detected in file 'C:\Users\...\test.xlsx'</summary>
-<repairedParts>
<repairedPart>Repaired Part: /xl/worksheets/sheet5.xml part with XML error. Load error. Line 1, column 0.</repairedPart>
</repairedParts>
When I am adding the content at the last row without using InsertRow everything is working fine.
Also, if I save the ExcelPackage immediately after using InsertRow the error is also present, so it definitely has something to do with this function (also if I am only using one Worksheet). After using InsertRow it seems like the whole formatting of the respective Excel Sheet is screwed up. The inserted content appears to be right though.
The excel is initially created from an empty template excel that contains nothing but the header names (also had the same issue with a template without anything inside):
The following code can be used to reproduce (this is just an example - in my case every sheet has more than 50 rows):
FileInfo filePath= new FileInfo(fileName);
excel = new ExcelPackage(filePath);
ExcelWorkbook wb = excel.Workbook;
foreach (ExcelWorksheet ws in wb.Worksheets)
{
int i = 5;
ws.InsertRow(i, 1);
//same effect with ws.InsertRows(i, 1, i-1)
ws.Cells[i, 1].Value = "test";
ws.Cells[i, 2].Value = "test";
//excel.Save();
}
excel.Save();
Although my answer is not based on EPPlus, have you looked at this post ?
Inserting new rows and moving exsisting ones with OpenXML SDK 2.0
I am guessing that you are getting errors because the newly added rows from the ws.InsertRow function are not updating the required row indexes. This is mentioned in the post.
Also there is a recommendation in the comments "To anyone who is getting an error when opening the file try this line before you save your document'... xlsFile.WorkbookPart.DeletePart(xlsFile.WorkbookPart.CalculationChainPart);

How to export Chart created in EPPlus to Image file

I have tried this;
var excelPicture = sheet.Drawings[0] as OfficeOpenXml.Drawing.ExcelPicture;
var img = excelPicture.Image;
However the excelPicture variable become null. How can I create image file from ExcelDrawing??
It seems that this can't be done via EPPlus API. There is the opened issue in the GitHub project repository how export the drawings to a file. But the provided solution in the question does not work (it seems #Onchomngebul himself wrote the the comment)
Alternative solution is to use Workbook class in Spire.XLS nuget-package (or via free version FreeSpire.XLS).
var workbook = new Workbook();
workbook.LoadFromFile(workbookFileName, ExcelVersion.Version2010);
var sheet = workbook.Worksheets[0]; // index or name of your worksheet
var image = workbook.SaveChartAsImage(sheet, 0); // chart index
img.Save(chartFileName, ImageFormat.Png);
For more details please see this comment in the issue.
Another solution is to try to use Excel.ChartObject. I think this question Exporting Excel Charts as Images may help you.

Excel Interop - Set filename before saving

Is it possible to set the excel filename before file saving?
I have following simple code:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
excel.Visible = true;
Excel.Workbook workbook = excel.Workbooks.Add(Excel.XlSheetType.xlWorksheet);
Excel.Worksheet sheet = workbook.Sheets[1];
sheet.Cells[1, 1] = "Hello World!";
Is it possible to predefine this name before saving?
Thanks.
There is no explicit, foolproof way to do this prior to saving, unfortunately. The closest you could come is to use a template. If you have a template called FOO.xltx, you could create your workbook like this:
Application.Workbooks.Add "X:\path\to\FOO.xltx"
The only quirk is that the name for the new documents will be appended with an incrementing number (FOO1 the first time, then FOO2,FOO3, etc.).
To create a template, just create a new document, and when you save it, select Excel Template (*.xltx) from the Save as type dropdown.
You have to use saveas to save the file with the filename you want. Then when the user clicks save it will just update the file that was previously created. Unfortunately there is no other way. Here is the code:
workbook.SaveAs(Filename: FILENAMEHERE);
Here is the MSDN doc for it: https://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.saveas.aspx

Microsoft Open SDK 2.0 to generate excel file using c#

Please refer link for the code i am using to generate excel file from data table. I am able to generate excel file successfully.
But the problem/Challenge/Question is as follows.
I Want to generate column as per the datatype so if Column value contains date the it cell format should be date(dd/mm/yyy) if number then numeric. ans so on...
I have tried to generate excel file as per data format you can see specific methods to generate cell value. But the problem is when user download the file it will gives the warning message that "Excel found unreadable content 'filename'. Do you want to recover the content of this workbook?". I don,t want that warning message should come.
If I am writing everything as text without format then file will open without any warning message and after downloading file, if user tries to format respective column in date or number format then also it will not allow user to format/slice & dice data in excel file.
Reference :- http://www.codeproject.com/Articles/263106/Export-Tabular-Data-in-CSV-and-Excel-Formats-Throu
Please let me know the solution if anybody has.
I am using DocumentFormat.OpenXml.dll
private Cell CreateTextCell(string header, UInt32 index, string text)
{
var cell = new Cell {DataType = CellValues.InlineString, CellReference = header + index};
var istring = new InlineString();
var t = new Text {Text = text};
istring.Append(t);
cell.Append(istring);
return cell;
}
private Cell CreateDateCell(string header, UInt32 index, DateTime sDate)
{
Cell cell = new Cell();
cell.DataType = CellValues.Date;
cell.CellReference = header + index;
cell.StyleIndex = UInt32Value.FromUInt32(14);
cell.CellValue = new CellValue { Text = sDate.ToOADate().ToString() };
return cell;
}
private Cell CreateNumberCell(string header, UInt32 index, string text)
{
Cell cell = new Cell();
cell.DataType = CellValues.Number;
cell.CellReference = header + index;
cell.CellValue = new CellValue(text);
return cell;
}
I have moved to EPPlus .net library to generate excel file and it is very easy to use.
Thanks.
I may not have the complete solution but you can try the below steps to find the root cause:
One of the reasons for unreadable content error (There are many reasons for this but considering that you are just writing from the datatable only).is if there is a mismatch between the StyleIndex/Datatype/Cellvalue format
To identify the root cause you can try:
Create a sample excel and directly write a cell (only a cell) with number, it that goes on fine, try the next datatype one by one.
Next try to write them one after the other.
Do this and sort down the types which are causing problems.
Next try to vary the StyleIndex/cellFormat with that type (you can check for examples online) till the format is fine without error. Once you are good with all types, you can try writing to the entire excel.
You can also use this method if you want to try something new using OpenXML (since you do not have well documented examples for everything Online)
Another way to identify issues is to use Openxml productivity tool and do a validation of the file.

how to create and download excel document using asp.net

How to create and download excel document using asp.net ?
The purpose is to use xml, linq or whatever to send an excel document to a customer via a browser.
Edit : Use case
The customer load a gridview ( made with ajax framework ) in a browser, the gridview is directly linked to an sql database.
I put a button 'export to excel' to let customer save this gridview data on his computer ansd i would like to launch a clean download of an excel.
The solutions proposed here are not clean, like send an html document and change the header to excel document etc, i'm searching a simple solution on codeplex right now, i will let you know.
Starter kit
First i have downloaded the Open XML Format SDK 2.0.
It comes with 3 useful tools in :
C:\Program Files\Open XML Format SDK\V2.0\tools
DocumentReflector.exe wich auto
generate the c# to build a
spreadsheet from the code.
OpenXmlClassesExplorer.exe display
Ecma specification and the class
documentation (using an MSDN style
format).
OpenXmlDiff.exe graphically compare
two Open XML files and search for
errors.
I suggest anyone who begin to rename .xlsx to .zip, so you can see the XML files who drive our spreadsheet ( for the example our sheets are in "xl\worksheets" ).
The code
Disclaimer : I have stolen all the code from an MSDN technical article ;D
The following code use an *.xlsx template i made manually to be able to modify it.
Namespaces references
using System.IO;
using System.Xml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
// Database object
DataClassesDataContext db = new DataClassesDataContext();
// Make a copy of the template file.
File.Copy(#"C:\inetpub\wwwroot\project.Web\Clients\Handlers\oxml-tpl\livreurs.xlsx", #"C:\inetpub\wwwroot\project.Web\Clients\Handlers\oxml-tpl\generated.xlsx", true);
// Open the copied template workbook.
using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(#"C:\inetpub\wwwroot\project.Web\Clients\Handlers\oxml-tpl\generated.xlsx", true))
{
// Access the main Workbook part, which contains all references.
WorkbookPart workbookPart = myWorkbook.WorkbookPart;
// Get the first worksheet.
WorksheetPart worksheetPart = workbookPart.WorksheetParts.ElementAt(2);
// The SheetData object will contain all the data.
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
// Begining Row pointer
int index = 2;
// Database results
var query = from t in db.Clients select t;
// For each item in the database, add a Row to SheetData.
foreach (var item in query)
{
// Cell related variable
string Nom = item.Nom;
// New Row
Row row = new Row();
row.RowIndex = (UInt32)index;
// New Cell
Cell cell = new Cell();
cell.DataType = CellValues.InlineString;
// Column A1, 2, 3 ... and so on
cell.CellReference = "A"+index;
// Create Text object
Text t = new Text();
t.Text = Nom;
// Append Text to InlineString object
InlineString inlineString = new InlineString();
inlineString.AppendChild(t);
// Append InlineString to Cell
cell.AppendChild(inlineString);
// Append Cell to Row
row.AppendChild(cell);
// Append Row to SheetData
sheetData.AppendChild(row);
// increase row pointer
index++;
}
// save
worksheetPart.Worksheet.Save();
}
I havent finished yet, my second job is to auto download the spreadsheet after modification.
Finally, i redirect the user to my generated spredsheet (from my aspx)
context.Response.Redirect("Oxml-tpl/generated.xlsx");
just set Response.ContentType = "application/vnd.ms-excel" and your page will rendered as an excel sheet on the clients browser
Sample code here
There are quite a few ways of handling this, depending on how extensive the Excel functionality is. Binoj's answer works if the Excel is just a spreadsheet and has no direct Excel functionality built in. The client can add functionality, concats, etc. These are "dumb" excel docs until the client does soemthing.
To create a more full featured Excel doc, you havve two basic choices that I can think of offhand.
Use either the office components (re: bad) to create an excel document, or a third party component, like SoftArtisan's ExcelWriter. Great component, but there is a cost.
Use a control on the page that allows export to Excel. Most vendors of ASSP.NET controls have this functionality on their grids.
Option #1 allows you pretty much all functionality of Excel. Option #2 is a bit more limited, at least in the controls I have tried.
Good article on how top export to excel from Erika Ehrli
http://blogs.msdn.com/erikaehrli/archive/2009/01/30/how-to-export-data-to-excel-from-an-asp-net-application-avoid-the-file-format-differ-prompt.aspx

Categories