简体   繁体   中英

Export and format data into Excel from C#

I know this topic has been discussed but I think it has some differences. I have some list of object which I want to copy to Excel. I need to format the appearance of the spreadsheet too, if possible from Excel. I've been said that was some kind of Excel Automation library or so that allows yo to build a spreadsheet from code. This way I should be able to create that document and later open it. Any ideas on that matter? Thanks!

If you creating a typical excel document that does not use Advanced features of Excel, a library like NPOI http://npoi.codeplex.com/ or at http://code.google.com/p/npoi/ renders well. Or another one called ExcelLibrary. I have personally used the NPOI library with a lot of ease. There are known complexities/problem with server-side office automation: http://support.microsoft.com/kb/257757 . NPOI is suited for producing xls (pre 2007 Excel versions) files. If you are happy churning out xslx (post 2007 Excel versions) files, use the OpenXML - It is able to support almost all the features you might need on your xslx document

You can export data to Excel from C#, can you give us more info about the objects you want to do the export from, if for instance you need to create and open an excel document from a Listview this is how you'd do it:

First you need to add Microsoft.Office.Interop.Excel as a reference to the project and add the following assembly to your code: using Excel = Microsoft.Office.Interop.Excel;

   //This would convert the listview1 content to Excel document and create the file in the given path        
    private void CreateExcelFromListview()
    {
        ListViewExport.ListViewToCsv(listView1, "C:\\test.csv", true);
        OpenInExcel("C:\\test.csv");
    }

    //This would open the document on screen
    public void OpenInExcel(string strFileName)
    {
        try
        {
            new Excel.Application {Visible = true}.Workbooks.Open(strFileName);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

In case you have no joy with the OpenXML or other libraries suggested so far, you might care to look at Aspose.Cells . I've used it to good effect in two different projects without issue (it did have some color formatting quirks, but they could be worked around).

It lets you read and build Excel files (in all versions), declare formulae in cells and a heap more, and does not require Excel on the end workstation.

However, it may be overkill for your stated needs - it is not cheap starting at $999, and gets rapidly more expensive the wider you want to develop and deploy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM