Can anybody tell me how to set the zoom factor on an Excel sheet via a ASP.NET application. I believe the Excel Sheet object has a PageSetup.Zoom property which does not seem to be working. When I generate a report in Excel programatically through ASP.NET I get the zoom factor of all sheets in the workbook as 100%.
Here is a code sample
oSheet.PageSetup.CenterHorizontally = true;
oSheet.PageSetup.CenterVertically = true;
oSheet.PageSetup.Orientation = XlPageOrientation.xlPortrait;
oSheet.PageSetup.PaperSize = XlPaperSize.xlPaperA4;
oSheet.PageSetup.Order = XlOrder.xlDownThenOver;
oSheet.PageSetup.Zoom = 85;
Another option is ActiveWindow.Zoom as generated by a macro but it is macro-specific. The whole point of asking this question is after the report has been generated the zoom factor of all the pages in the Excel workbook should be 85%.
Any inputs would be highly appreciated.
SpreadsheetGear for .NET allows you to set the zoom factor of an Excel worksheet like this:
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets[0];
worksheet.WindowInfo.Zoom = 150;
Microsoft does not support and recommends against using Office with COM Interop in ASP.NET (see this Considerations for server-side Automation of Office KB article).
You can see live C# and VB examples which demonstrate using SpreadsheetGear from ASP.NET here and download a free trial here.
Disclaimer: I own SpreadsheetGear LLC
PageSetup only affects printing. You need to use the Window Zoom. In C# it's something like:
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.ActiveWindow.Zoom = 150;
This only affects the sheet in the active window, not every sheet. You can also set the zoom through the workbook (wbk.Windows[0].Zoom) rather than xlApp.ActiveWindow.
The way to implement this for all sheets in a Workbook object MyWorkbook is to select all of the sheets and then hit the ActiveWindow:
MyWorkbook.Sheets.Select(Type.Missing);
MyWorkbook.Windows[1].Zoom = 150;
I tested this and Windows[1] seems to give you document-level customization. I had a problem embedding this code in the workbook's Startup event, but it seems to be fine further down the line.
Related
I've got several XtraGrid Controls each one containing different information, I get some information about the way in which you can export a XtraGrid to an Excel file in the following direction http://www.devexpress.com/Support/Center/p/Q362120.aspx
Now Is there any way to export the each XtraGrid Control to a single Excel file so that every XtraGrid information is exported to a different excel sheet.
I tried setting the exporting path direction to the same Excel file, but when the first exporting process is done, the second exporting process just overrides the excel file and so on.
I tried using the method described in this direction XtraGrid - Export To Excel , but I wanted to know if there is another way whithout using the interop excel libraries because I have experience some problems when using this library (I mean when using this library you create an Excel process but after you created it you cannot kill it, even though you have used the method that is supposed to do that).
Any help would be welcomed.
I just wanted to provide a more complete answer, since it took a while for me to get a solution together using D..'s answer.
And yes - it looks like I'm trying to print something, but I'm just exporting to Excel, I promise.
using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;
using DevExpress.XtraGrid;
class whatever
{
GridControl grid1;
GridControl grid2;
//.....
public void exportToExcel()
{
using (var saveDialog = new SaveFileDialog())
{
saveDialog.Filter = "Excel (.xlsx)|*.xlsx";
if (saveDialog.ShowDialog() == DialogResult.OK)
{
var printingSystem = new PrintingSystemBase();
var compositeLink = new CompositeLinkBase();
compositeLink.PrintingSystemBase = printingSystem;
var link1 = new PrintableComponentLinkBase();
link1.Component = grid1;
var link2 = new PrintableComponentLinkBase();
link2.Component = grid2;
compositeLink.Links.Add(link1);
compositeLink.Links.Add(link2);
var options = new XlsxExportOptions();
options.ExportMode = XlsxExportMode.SingleFilePageByPage;
compositeLink.CreatePageForEachLink();
compositeLink.ExportToXlsx(saveDialog.FileName, options);
}
}
}
}
Hope it saves somebody a little time.
To do that you will want to add a printableComponentLink to each gridControl, and then Create a compositeLink that you can add each of the printableComponent links to.
This link may prove DevExpress KB Article may prove useful as it has an example of that.
Then you will use the compositeLink.ExportToXlsx method. If you create XlsxExportOptions with the XlsxExportOptions.ExportMode property equal to SingleFilePageByPage and pass it to the CompositeLink.ExportToXlsx method, every page will be exported to a separate sheet.
In above code, compositeLink.ExportToXlsx failed for me--no such method. Of course I am using V10.2.5, which is old. I suggest this link from the DEVXPRESS site that uses the ShowPreviewDialog method which allows exporting in a number of different formats. The link also shows how to do some customization of the output.
https://documentation.devexpress.com/#WindowsForms/clsDevExpressXtraPrintingLinksCompositeLinktopic
I am actually bit confused to say. I googled for applying styles in my spreadsheet i got some functions in which they mention about the font, borders etc which i need but i dont know where should i use or how should i implement.
When i tried to implement like
cell.StyleIndex=8 // Which is modified as per my need but there is no effect in the cells
can any one help me what can be the issue and where would i done the mistake
OpenXml is one of those really complex framework that could use a framework to make certain common tasks easier. I would suggest starting with the OpenXml Productivity Tool (available in the SDK). Create a spreadsheet that has the styles you want, save it, then open it in the tool to view the code necessary to create the style you would like.
Basically, there is a stylesheet section within the workbook that contains the various formats that are available to your document. These formats are sequential and may be accessed via their index (the StyleIndex you mentioned above.
So, it's Friday. Enough talk, let's look at some code:
// Obtain a handle to the stylesheet
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
Stylesheet stylesheet = workbookPart.WorkbookStylesPart.Stylesheet;
// Highlight format
CellFormat highlightPriceFormat = new CellFormat { NumberFormatId = (UInt32Value) 164U, FontId = (UInt32Value) 1U, FillId = (UInt32Value) 2U, BorderId = (UInt32Value) 0U, FormatId = (UInt32Value) 0U, ApplyNumberFormat = true, ApplyFont = true, ApplyProtection = true };
highlightPriceFormat.AppendChild(new Protection { Locked = false });
stylesheet.CellFormats.AppendChild(highlightPriceFormat);
The code above first obtains a handle to the workbook, then the worksheet, and finally the stylesheet for the worksheet. Once obtained, we create a new cell format that is based on the Currency format and highlighted in yellow.
I hope this is enough to get you started. There is information out there, but it is in bits-and-pieces all over the internet. This related question has another great example.
I was using a company called ActiveXLS to save native XLS files with charts from Classic ASP but they seem to have closed down.
Can anyone recommend an alternative classic asp excel component I can use?
CSV or HTML (with XLS content type) export is not sufficient for what I need.
You can access the MS Excel DOM using Classic ASP. There are definite limitations of this approach for a web based environment but I have used it for low volumes.
Here's some sample code to illustrate:
Set oApp = Server.CreateObject("Excel.Application")
Set oBook = oApp.Workbooks.Add
Set oSheet = oBook.ActiveSheet
Set oRange = oApp.ActiveCell
' Create the header fields
oRange.Cells(1,1) = "Column 1"
oRange.Cells(1,2) = "Column 2"
oSheet.Range(oSheet.Cells(1,1), oSheet.Cells(i,j)).Select
oApp.Selection.Columns.AutoFit
oSheet.Cells(1,1).Select
oBook.SaveAs "filename.xls"
oBook.Close
oApp.Quit
Set oApp = Nothing
This does require Excel to be installed on the server that builds these files.
I use excel through vb.net/asp.net to generate reports from a web page and then send the file down to the user. We've had some issues with Excel being super slow/inefficient/not closing (even when we keep track of the process id and try to kill it in code...). So I'm looking for some flexible alternatives. We need a replacement that can:
Allow for inidivdual cell formatting including borders (different settings on each side), background colors, font styles/coloring, etc...
Allow for cell merging
Allow for formatting (bolding in this case) of a portion of the text inside of a cell while leaving the rest of the text unchanged
Image insertion/repositioning inside a cell (not crucial)
Multiple Worksheets per Workbook
These are all the features I can think of off hand, any help or suggestiong at alternative libraries to look at would be appreciated. We are running Excel 2007 on the server but we are rolling out Office 2010 to clients so I think that might open the doors for some more supported file formats, if that helps.
After looking through the various options and performing more independent research I ended up using EPPlus, which you can get # http://epplus.codeplex.com.
Thanks for all the suggestions.
I recommend you to use the DevExpress.XtraReports from DevExpress. It is a Licensed product, but offers you a friendly toolkit for generating great and complexity reports. It is well documented and easy to use, once you define a template (REPX) you can populate it with data by assigning to each element a value as well as using [mail merge] feature which will be automatically replaced once you bind with data the report. In the core of such technology is a well OO design of classes. Once you generate the report you can export it to the most common formats: XLS, HTML, PDF, RTF...
public void GenerateReportFile(string rptFileName, string param1, int param2)
{
XtraReport report = null;
try
{
report = new XtraReport();
//-- loads the layout template (repx file)
report.LoadLayout("SomeDirectory\report_template.repx");
//-- assign data to report controls
report.FindControl("Label1", true).Text = string.Format("{0:dd/MM/yyyy}", fecha1);
report.FindControl("Label2", true).Text = string.Format("{0:dd/MM/yyyy}", fecha1);
//-- gets data from some Data Acces Layer method and assig it to the report DataSource property
DALReport dal = new DALReport();
report.DataSource = dal.GetReport1Data(ExpEmp, param1, param2);
report.DataMember = "data";
report.ExportToPdf(rptFileName, options);
}
catch { throw; }
finally { if (report != null) { report.Dispose(); } report = null; }
}
For more information refers to: http://demos.devexpress.com/XtraReportsDemos/
There is another free library for .Net iTextSharp, this library
was originally written for Java, then was translated to C# for .Net
usage. The library is mainly for PDF documents creation but some
versions also supports XLS documents creation.
GNU plot is a little bit of a pain to get to run on windows but it is a an awesome tool
It sounds like you are using a library that opens Excel and uses MS Office Excel objects to create the Excel file. Since you are using 2007 and above, you may want to consider creating the Excel file manually using a library that creates the XML (therefore, Excel doesn't open at all).
Check out ExcelLibrary.
While doing a search on this, I found this page (on StackOverflow) that provides some sample code.
Office Web Components (though dated) is free and has worked for me in the past.
If you want to spend the loot, Aspose Cells is a good way to go also.
Is it possible to generate PDF Documents in an Adobe AIR application without resorting to a round trip web service for generating the PDF? I've looked at the initial Flex Reports on GoogleCode but it requires a round trip for generating the actual PDF.
Given that AIR is supposed to be the Desktop end for RIAs is there a way to accomplish this? I suspect I am overlooking something but my searches through the documentation don't reveal too much and given the target for AIR I can't believe that it's just something they didn't include.
There's AlivePDF, which is a PDF generation library for ActionScript that should work, it was made just for the situation you describe.
Just added a Adobe Air + Javascript + AlivePDF demo:
This demo doesn't require flex and is pretty straight forward.
http://www.drybydesign.com/2010/02/26/adobe-air-alivepdf-without-flex/
One of the other teams where I work is working on a Flex-based drawing application and they were totally surprised that AIR / Flex does not have PDF authoring built-in. They ended up rolling their own simple PDF creator based on the PDF specification.
Yes it is very easy to create PDF using AlivePDF, here is the sample code, first method create a pdf and second method save the pdf on disk and return the path, feel free to ask any question.
public function createFlexPdf() : String
{
pdf = new PDF();
pdf.setDisplayMode (Display.FULL_WIDTH,Layout.ONE_COLUMN,Mode.FIT_TO_PAGE,0.96);
pdf.setViewerPreferences(ToolBar.SHOW,MenuBar.HIDE,WindowUI.SHOW,FitWindow.RESIZED,CenterWindow.CENTERED);
pdf.addPage();
var myFontStyle:IFont = new CoreFont ( FontFamily.COURIER );
pdf.setFont(myFontStyle,10);
pdf.addText('Kamran Aslam',10,20);//String, X-Coord, Y-Coord
return savePDF();
}
private function savePDF():String
{
var fileStream:FileStream = new FileStream();
var file:File = File.createTempDirectory();
file = file.resolvePath("temp.pdf");
fileStream.open(file, FileMode.WRITE);
var bytes:ByteArray = pdf.save(Method.LOCAL);
fileStream.writeBytes(bytes);
fileStream.close();
return file.url;
}