I have an object with a lot of subqueries and I want do export to excel just like Linqpad does, here is an example:
Any help?
Tks
If you include a reference to linqpad.exe in your project, you can then use it to do the export to html
eg,
List<User> users = ....
var filename = "test.html";
var writer = LINQPad.Util.CreateXhtmlWriter();
writer.Write(users);
System.IO.File.WriteAllText(filename, writer.ToString());
// Open the file in excel
Process.Start("Excel" , filename);
Excel can actually open an HTML doc, renamed "xls" - reading-in HTML table structures as Excel cells.
You'd have to output your data as HTML, though.
As noted, LinqPad is not really export to an Excel format. but it create an HTML file, and opens it with Ms-Excel.
(but for a download file, you cant force the client how open th file, but you can naming the extension to XLS, and EXCEL open it with a warning).
for generate the HTML output, LinqPad use the hyperlinq library.
void Main()
{
var filePath = Path.GetTempPath() + "output.html"; //or output.xls but with ms-excel warning
var iEnumerbleValue = Enumerable.Range(1, 500).Select(e => new { a = 1, b = e });
File.WriteAllText(filePath, CreateHtml(iEnumerbleValue).ToString());
Process.Start("EXCEL.EXE", filePath);
}
HDoc CreateHtml<T>(IEnumerable<T> coll)
{
var fields = typeof(T).GetProperties();
return H.Doc(
H.head(H.style()),
H.body(
H.table(
H.tbody(
H.tr(fields.Select(f => H.th(f.Name))),
from item in coll
select H.tr(
fields.Select(f => H.td(f.GetValue(item)))
)
)
)
)
);
}
I wanted to add this solution for the next person who comes searching. I realize it's an old question, but it's the only one that popped up in my search.
You can run lprun on the command line.
lprun -format=html yourQuery.linq > output.xls
Excel is able to open html as long as it's xls extension and not xlsx. If you use xlsx it will complain that it's in the wrong format and fail to open. With xls extension it gives a message, but it is able to open.
Just as a note-
I needed a database connection string for entity framework. I had it in the linqpad.config and it took me a while to figure out why lprun couldn't read it. You have to add the connection string section to lprun.exe.config so lprun can use it.
Related
I use the EPPlus library to batch edit some existing XLSM files. Inside the files I replace a line of VBA code and that's it. Everything works nice, if I edit the same line in the Excel code editor by hand.
When I open some of the files with Excel 2013 (15.0.4989.1000), the following error message is shown.
We found a problem with some content in 'test.xlsm'. Do you want us to
recover as much as we can? If you trust the source of this workbook,
click Yes.
If I click yes, the repair report shows the following entry. But the message is somewhat too generic to help me further.
Removed Records: Named range from /xl/workbook.xml-Part (Arbeitsmappe)
This is my C# code, which edits the XLSM file. Can I update my code or do I have to update the XLSM-file before editing it?
static void PatchVba(string filePath, string oldCode, string newCode)
{
var wbFileInfo = new FileInfo(filePath);
using (var package = new ExcelPackage(wbFileInfo, false))
{
foreach (var m in package.Workbook.VbaProject.Modules)
{
if (m.Code.Contains(oldCode))
{
m.Code = m.Code.Replace(oldCode, newCode);
Console.WriteLine("VBA Patched in \"{0}\"", filePath);
}
}
try
{
package.SaveAs(wbFileInfo);
}
catch
{
Console.WriteLine("Could not save patched file \"{0}\".", filePath);
}
}
}
I found out what the problem is. In the edited XLSM-file, a range name is used multiple times with overlapping scope. I was too focused on my C# code to find the root cause.
So removing the named ranges solves the issue. But it would still be interesting to know, why I can edit it without problems using Excel, but not by using EPPlus.
I have a folder with many csv files with the same format (same table structure but different data). I want to have all of the data from these csv files as a single data set inside my SSIS package. My current solution is this: Create a helping table in SQL Server and use a For Each Container to load all the files into the table. Then load this table as the single data set you want in the SSIS package.
However, I would highly prefer a method that does not depend on creating such an extra table in my SQL Server. I was thinking that there might be a better way of doing this using C# and Script component. Does anybody has any suggestions?
How about:
var allCsv = Directory.EnumerateFiles("Src-Path", ".*csv", SearchOption.TopDirectoryOnly);
string[] header = { File.ReadLines(allCsv.First()).First(l => !string.IsNullOrWhiteSpace(l)) };
var mergedData = allCsv
.SelectMany(csv => File.ReadLines(csv)
.SkipWhile(l => string.IsNullOrWhiteSpace(l)).Skip(1)); // skip header of each file
File.WriteAllLines("Dest-Path", header.Concat(mergedData));
Just note that you have to add using System.Linq;
This should do it for you.
var allCsv = Directory.EnumerateFiles("Src-Path", ".*csv", SearchOption.TopDirectoryOnly);
string[] header = { File.ReadLines(allCsv.First()).First(l => !string.IsNullOrWhiteSpace(l)) };
var mergedData = allCsv
.SelectMany(csv => File.ReadLines(csv)
.SkipWhile(l => string.IsNullOrWhiteSpace(l)).Skip(1)); // skip header of each file
File.WriteAllLines("Dest-Path", header.Concat(mergedData));
http://www.sqldataplatform.com/Blog/Post/49/How-to-Combine-CSV-Files-Using-a-Simple-C--Script
Note, you don't even need C# for something as simple as this! You can actually use the Command Prompt for something that is completely standardized.
Open Command Window. (Press "Window Key" and "R", then type command and enter.
Type copy c:\*.csv c:\File.csv and press enter
This will combine all of the csv files that are in your root c:\ directory into one file called File.csv.
You can change the file names and paths as necessary.
I'm using EPPlus in C# to read an Excel (.xlsx) file. The initialization is done like this:
var package = new ExcelPackage(new FileInfo(filename));
This works fine but is there any way to check if the specified filename or package is actually a valid .xlsx file? Otherwise there will be exceptions when operating on a non-Excel object, e.g. if the user accidentially opens a .zip file or else.
You can check the extension of your file:
string file = #"C:\Users\Robert\Documents\Test.txt";
string extenstion = Path.GetExtension(file);
Update
I havent found some kind of return values for the situation that some file cannot be open in the EPPlus documentation, but you can use this to catch the excetptions:
FileInfo fileInfo = new FileInfo(pathToYourFile);
ExcelPackage package = null;
try
{
package = new ExcelPackage(fileInfo);
}
catch(Exception exception)
{
...
}
If you are not in catch - thats mean it was opened correctly.
I need to make to following snippet of code work in the context of an open file. This code needs to run in an Excel add-in to write the currently open document to a database. At line 3, System.IO.File.ReadAllBytes() an error occurs indicating that the document is currently in use. Is there an equivalent method that I can use that will work on an open document? If not, what is the solution?
Foo.DataClasses1DataContext db = new Foo.DataClasses1DataContext();
string ThisDocument = Globals.ThisAddIn.Application.ActiveWorkbook.FullName;
byte[] inputBuffer = System.IO.File.ReadAllBytes(ThisDocument);
Foo.RFP_Document rfpDocument = new Foo.RFP_Document();
rfpDocument.DocumentName = "Some Name";
rfpDocument.DocumentFile = new System.Data.Linq.Binary(inputBuffer);
db.RFP_Documents.InsertOnSubmit(rfpDocument);
db.SubmitChanges();
Here's a link to a similar question related to VB. How do I copy an open file in VB6?
You could just save a copy of the file using Workbook.SaveCopyAs, use this one and delete it afterwards.
I have to automate something for the finance dpt. I've got an Excel file which I want to read using OleDb:
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=A_File.xls;Extended Properties=""HTML Import;IMEX=1;""";
using (OleDbConnection connection = new OleDbConnection())
{
using (DbCommand command = connection.CreateCommand())
{
connection.ConnectionString = connectionString;
connection.Open();
DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if( (null == dtSchema) || ( dtSchema.Rows.Count <= 0 ) )
{
//raise exception if needed
}
command.CommandText = "SELECT * FROM [NameOfTheWorksheet$]";
using (DbDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
//do something with the data
}
}
}
}
Normally the connectionstring would have an extended property "Excel 8.0", but the file can't be read that way because it seems to be an html file renamed to .xls.
when I copy the data from the xls to a new xls, I can read the new xls with the E.P. set to "Excel 8.0".
Yes, I can read the file by creating an instance of Excel, but I rather not..
Any idea how I can read the xls using OleDb without making manual changes to the xls or by playing with ranges in a instanciated Excel?
Regards,
Michel
I asked this same question on another forum and got the answer so I figured I'd share it here. As per this article: http://ewbi.blogs.com/develops/2006/12/reading_html_ta.html
Instead of using the sheetname, you must use the page title in the select statement without the $. SELECT * FROM [HTMLPageTitle]
I've been searching so many solution, end up I found something really simple and easy -
to import XML file to Excel file, I tried to convert XML to HTML first, use -
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
then I found I could easily change my output file as .xls, instead of .html
//create the output stream
XmlTextWriter myWriter = new XmlTextWriter
("result.html", null);
then the output is perfect Excel file from my XML data file.
hope this will save ur work.
I have run into the same problem. As previously mentioned, it seems to be an html file renamed to .xls. When I copy the data from the xls to a new xls, I can read the new xls with the E.P. set to "Excel 8.0".
In this scenario, the file couldn't be saved in the correct format. So we have to convert that file to the correct format. To do this, use MS Office Excel 2007, Click File -> Convert. The file will be converted to the right format automatically.