Producing more complex excel worksheets using c# - c#

I am required to produce a somewhat complicated excel workbook containing over 30 worksheets, each using information from several database tables to dynamically draw several tables per sheet, with formating. I have used c# in the past although I am unfamilar with its use in Excel. Any recomendations regarding to how to format and posistion cells dynamically from a database would be a great help.
Thanks in advance.

Visual Studio Tools for Office (VSTO) is your friend :) I use this all the time to build complex worksheets. This is way, way better than importing from CSV or using some kind of wacky DB connectivity.
Here are some links
MSDN
Blog
Wikipedia
This is very easy to do, though there are a few oddities. I find it very effective to use the Excell MACRO recorder to record actions, then look at the source and re-impliment in C#. The object model is exactly the same between VB and C#.
VSTO is part of Visual Studio 2008. I looked on the product page, but I cannot determine if it comes with VS2008 C# Express Edition. The easiest thin to do is just download it and see :)

Your question sounds like you already understand the technology involved, so this answer is restricted to formatting & layout.
I did something very similar 10 years ago. It's been a while, but here's what I figured out.
Put all calculated & summary info on top. (including 'bottom line' totals)
Base charts on the totaled cells at the top of the sheets since they don't move.
Put all charts, summaries, etc on their own sheet.
If there are calculations involved, make each step of the process available so the user can step through them. This will prevent you spending countless hours proving your code calculates according to spec, if you don't do this, your 'black box' calculations will be questioned constantly.
If they don't want to see the raw data, only the calculations, then consider pushing it out to a hidden sheet.
Store a template workbook with your app, then just copy it so you can do all formatting in XL, not code.
One thing you really want to avoid is keeping track of different cell locations. You want to push values into cells which are always in the same location.

I find a very effective and often underused feature in Excel is the Web Query.
If you can present your data in a website, you can pre-build your Excel workbook with web queries set up to gather the data from the website on demand, which is presented in the form of tables in appropriate web pages.
You can add query string parameters for passing arguments to the web page and you can set auto-refresh, formatting preservation, etc. PivotTables/Charts can refer to the data and can made up to update upon data refresh with a few lines of VBA, for example.
This is often a much simpler solution than VSTO if it can meet the requirements.
Another option would be to use a third party Excel file generation assembly.

Related

Calculation using Excel formula from C#

I have an excel sheet with a complex formula applied in it. I want to use this formula from my C# code for some calculations. My scenario is like this User fill a form (web) and submit, our program will fetch these values and applied in the hosted excel sheet and get the result.
is this possible?
Help is highly appreciable.
Thanks,
This really should go in the comments section, as I have a few questions to clarify your request. However, as I do not yet have the reputation, my questions must go here.
Is it a formula residing in your existing Excel document that you want to utilize that formula/document without re-writing the code?
Or are you asking if it is possible to write the same formula that you have working on the Excel sheet in c#?
If the former, it is conceivable to pass data into the Excel sheet from the code. After all we can use code to append to other document types, why not an Excel document? And if we can fetch specific lines from other document types, why not from an Excel document (especially since the grid/cell layout provides easier addressable points). However, while it is conceivable, doesn't mean it's easy. It's an interesting proposition, and I'd like to do some experiments on that.
If it is the latter, then depending on the formula's requirements, you may just need to use the appropriate math libraries and write out the formula directly in the c# code. You may not be able to visually see how everything ties together as nicely in the Excel document (with the referenced cells highlighted), but you could modularize components of the formula more easily as sub-functions and re-use values easily enough with variables.

Complex reports from C# programatically into office Word

First of all I want to say hi to the programming community, what I am looking for is a way to generate a report from my Windows Forms Application in word preferably, this report is basically a list of pre-configured days in a tour creation software I am creating.
I have searched everywhere and I cant seem to find information on how to start creating the report, I have all the information saved into a database, I just need to be able to get this information into word and ordered as it should be ordered.
I just want to be pointed in the right direction so I can research on it even further.
The exact thing I want to create is a word file that I wish I could share here so you can actually see what I mean.
Thank you for all your attention and help if possible.
I can point you in the right direction. Word documents are stored in a format called OpenXml which can be created and manipulated without actually using Word directly. That's good because you don't want to deal with code that actually starts an instance of Word and automates it (Interop.) It sort of works but it's not something I recommend dealing with ever.
OpenXml isn't fun either, but it's better. You can create your document "normally" using Word, save it, and then have your application use it as a template, opening a copy, populating some data, and then saving it.
Here's the reference for OpenXml with Word. I'm not saying it's pretty. It's not. The documentation is lacking. This page on adding text isn't linked from the previous page, even though many other topics are.
There are some nuget packages like this one that can help.
I once did a POC that did exactly what you're describing by opening and altering a document used a template using OpenXml. I'll see if I can dig up the code. But this is definitely a good direction to look in if Word is an absolute requirement.
This is a long shot, but can you output in HTML? If you can that's an even easier alternative.
Can you use Excel? That's also OpenXml but there's easier-to-use tools like EPPlus that simplify dealing with it, because it's not just the friendliest thing to work with.
An option that I would suggest is Crystal Reports. You can download the Crystal Reports add-in for Visual Studio for free from here. Crystal Reports is an easy way to perform reporting from various data sources including SQL. There are also a lot of free tutorials online for learning how to use CR. The syntax is a little strange, but it is easy enough to use.
The add-in allows you to create reports for your application and also build applications that can display, print, and export Crystal Reports.
You can export reports to .RTF (Rich Text Format) files. MS Word can open, edit, and convert RTF documents. It does a fairly decent job, but special formatting might take some work. This route is a ton easier than trying to write XML or anything else. I've written several reports designed for export to RTF. My boss runs the report, exports it, then edits it in Word. He loves the reports.
If you are planning on developing a lot of reports, purchasing the full version of Crystal Reports is well worth it. I believe they are on version 2016 currently.
If you do want to deal with automating Word, Microsoft's guide "Automating Applications Using the Office Object Model" Word-specific task content is here: https://msdn.microsoft.com/en-us/library/78whx7s6(v=vs.80).aspx
A larger example: https://support.microsoft.com/en-us/kb/316384
To begin, simply add an assembly reference to your project file for the correct Office Object Library (example: "Microsoft Word ##.0 Object Library"). Note that you must have Office installed to take this approach.
Good luck!

How do I generate a PDF/Excel file from an SQL database using C# and MVC 2?

I need to make the information in the database usable by allowing the user to download it as a PDF or Excel spreadsheet (either one works, both is perfect).
I've looked around at a bunch of options, but I really can't decide which one I should use, let alone if any of those options are actually useful. Most of the options I've found revolve around converting already existing HTML files into PDFs which is not what I need. Also, it needs to be free. My bosses haven't given me a budget to spend on this
I'm not sure what other information I should include here.
Well, any help is greatly appreciated. If you have questions about missing information, I'll get it posted ASAP. I'm here all day, so I'll be able to respond to any comments very quickly.
EDIT: Oh wow! Huge thanks, guys, for the massive response! I got a ton of ideas. This is super-helpful. Thanks!
if you want to generate an Excel (or also a Word) you can use openXml. You can create a new document exactly the way you want from pure code.
OpenXml SDK page
The solution I usually propose to my clients in this situation is to use Sql Server Reporting Services (SSRS). You can use the ReportViewer control included with it in order to generate PDF's, Excel spreadsheets, XML files, CSV files, and others. If you need ad hoc reporting, there is a Report Builder available as well.
Barring that, you can use OpenXml to generate Excel spreadsheets and there are a host of PDF toolkits available.
Have you looked into the reportviewer control, which is part of Visual Studio?
It allows you to export the report in PDF or Excel format.
http://www.carlosag.net/tools/excelxmlwriter/sample
check this might be useful for you
There are lots of reporting solutions out there such as SQL Server Reporting Services(for which you might already have a license). Take a look at Reporting (free || open source) Alternatives to Crystal Reports in Winforms which can likely be applied to the web with a bit of serialization.
I would suggest thinking about rolling your own depending on the situation. You could use pdfsharp for the pdf export and EPPlus for excel. They are both very easy to use and, I'm pretty sure, available in nuget with a couple of clicks.
If you want to go the Excel route, i'd recommend this article from Stephen Walther entitled ASP.NET MVC Tip #2 - Create a custom Action Result that returns Microsoft Excel Documents. This uses an old trick of writing an HTML document with an Excel mime type. This is different than streaming a native Excel file. And it's fairly easy to change the to rendering a CSV file if you want to strip it down, and make it a more universal file. Just remember to double-quote all the fields if there's a possibility of commas showing up.
If what your doing isn't too complicated you can use CSV files. CSV stands for comma separated values, and it is what it sounds like. You can create simple tables and columns using commas. For example paste the following lines into a text file:
heading1,heading2,heading3
info1,info2,info3
info1,info2,info3
Save the text file as a .csv file and voila - an excel spreadsheet. Obviously it is extremely easy to build these looping object collections. Mind you if you need any complicated text formatting etc then it is not really the best option.

How to automatically fill Excel template

At work each three months we have to write reports about past activities. For writing reports we have been given Excel template which contains columns to describe activity, date, time spent for the activity some combo box elements to select predefined location and some formulas.
As it takes a lot of time to rewrite all the details from personal evidence I was thinking about writing an application to write personal evidence into database and at the end of month fill the Excel template with stored data.
Does anyone know for any good resource which could be helpful for creating a solution described above?
Thanks
I have a similar quest.
I have found this good article
http://www.leniel.net/2009/07/creating-excel-spreadsheets-xls-xlsx-c.html
If you are comfortable with xslt and you do not need complex Excel (with images and so on) try out SpreadsheetML, but it will generate very big files.
See my reply on this question how to convert ms excel xml using a simple stylesheet?

C# - Templated Printing from Object(s)

I'm in need of a solution to print or export (pdf/doc) from C#. I want to be able to design a template with place holders, bind an object (or xml) to this template, and get out a finished document.
I'm not really sure if this is a reporting solution or not.
I also don't want to have to roll my own printing / graphics code -- I'd like all display concerns handled in a template.
I initially think of this as something Crystal Reports can do (although I've never used CR), but I'm not sure if I'm abusing the system here -- I'm not really interested in binding ADO.NET datasets at the moment (screw datasets). Can Crystal deal with binding to objects?
Does SSRS or WPF play in this field too?
A subset of WPF-P is XPS which can be used to present your objects via databinding.
One of the best choices if you are already using WPF.
Google Keywords: XPS, FixedDocument, FlowDocument, WPF Printing
Might read through this thread:
http://groups.google.com/group/nhusers/browse_thread/thread/e2c2b8f834ae7ea8
Seems a lot of people like iTextSharp
http://itextsharp.sourceforge.net/
For Word docs, look into Word's Mail Merge feature and Word automation. I did this recently in a form letter printing project. Basically what I did was create a Word template file (file extension .dot) and in this template file I defined MergeFields in a standard form letter. My application queries a database for the records it needs to print and then for each record it returns it matches fields in the database with these merge fields and sends the result (the merged doc) to the printer.
It's working really well and if I had a link that gave a definitive explanation, I'd provide it (check back here, I'll see if I can't find the most useful ones). Hopefully I've provided enough keywords to let you find your own resources. I can go into more detail if you need.
I've never had to export PDF files but for a project I'm working on now I'll have to. For a free solution my research has lead to iTextSharp (like Will Shaver points out) but I've only done the initial investigations and I have found a few pay solutions I might end up resorting to.

Categories