Search code examples
vb.netlinq-to-sqlexport-to-excel

Datasource or Linq Result to excel with VB.Net


i have found alot of sh*** right now. But not the things that im looking for.

I need to export a LINQ query (or the Datasource of my DataGridview) to an existing Excel Spreadsheet. Lets Say after Cell A25

I have a Windows Form application using LINQ for the Databindings.

Any Suggestions or good Examples?

Thanks in Advance


Solution

  • I would recommend to use EPPlus because it's simple, powerful and works without having office/excel being installed with Excel 2007 spreadsheets(xlsx-files). It's license model is GPL.

    Dim excel As New ExcelPackage
    excel.File = New IO.FileInfo("C:\Temp\AnExcelFile.xlsx")
    If excel.File.Exists Then excel.Load(excel.File.Open(FileMode.Open))
    Dim ws As ExcelWorksheet = excel.Workbook.Worksheets.Add("Worksheet-Name")'must be unique and less than 31 characters long'
    ws.Cells(26, 1).LoadFromDataTable(dt, True) 'loading from DataTable, the 2.Parameter is PrintHeaders'
    ws.Cells(26, 1).LoadFromCollection(query, True)'loading by LINQ-Query'
    excel.Save()
    

    I don't think that you can use it for xls-files without problems. Have a look what Jan said: http://epplus.codeplex.com/discussions/253371

    No, only XLSX, but you can open it in Excel 2003 if you have the compatibility pack installed. If you need XLS, have a look at the NPOI project here on Codeplex.