English 中文(简体)
我如何用 c# 将 DataGrid 保存到 XLS?
原标题:How do I save DataGrid to XLS with c#?

我想在我的应用程序中添加一个将数据保存到 XLS( 旧的优异文件) 的能力 。

我在ASP.NET < a href=" http://www.codeproject.com/Tips/344604/Export-to-EXCEL- from-Databable-in-Charp-Net" rel=“nofollow”>这里看到一个如何做到这一点的例子,但我不知道这如何转化成用于桌面应用程序的c#代码。

我还看过极好的自动化,它看起来是这样的:

private void button1_Click(object sender, EventArgs e)
{
    Excel.Application xlApp ;
    Excel.Workbook xlWorkBook ;
    Excel.Worksheet xlWorkSheet ;
    object misValue = System.Reflection.Missing.Value;

    xlApp = new Excel.ApplicationClass();
    xlWorkBook = xlApp.Workbooks.Add(misValue);

    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
    xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";

    xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
    xlWorkBook.Close(true, misValue, misValue);
    xlApp.Quit();

    releaseObject(xlWorkSheet);
    releaseObject(xlWorkBook);
    releaseObject(xlApp);

    MessageBox.Show("Excel file created , you can find the file c:\csharp-Excel.xls");
}

private void releaseObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    catch (Exception ex)
    {
        obj = null;
        MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
    }
    finally
    {
        GC.Collect();
    }
}

我不想使用它,因为:

  1. 如果我输出大量数据 将会是乌伯斯洛

  2. 我希望这在个人电脑上工作, 如果可能的话, 没有安装 微软ExcEx Excel 。

我还尝试了", http://www.carlosag.net/Tools/ExcelXmlWriter/" rel=“nofollow” >CarlosAg.Excel.Xml , 似乎奏效了, 但当我打开文件时, 我从优异之处得到警告, 文件不是 XLS格式, 而是其他格式 。

谁能推荐我免费的c#图书馆, 或教我如何使用常规的. Net 图书馆将数据保存到 XLS?

最佳回答

使用 < a href=> http://npoi.codeplex.com/" rel="nofollow" >NOPI ,可在 codeplex.com 上查阅。

This project is the .NET version of POI Java project at http://poi.apache.org/. POI is an open source project which can help you read/write xls, doc, ppt files. It has a wide application.

在此举例说明如何使用NOPI:

        using (FileStream fileOut = new FileStream("poi-test.xls", FileMode.OpenOrCreate))
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            var worksheet = workbook.CreateSheet("POI Worksheet");

            // index from 0,0... cell A1 is cell(0,0)
            var row1 = worksheet.CreateRow((short)0);

            var cellA1 = row1.CreateCell((short)0);
            cellA1.SetCellValue("Hello");
            ICellStyle cellStyle = workbook.CreateCellStyle();
            cellStyle.FillForegroundColor = HSSFColor.GOLD.index;
            cellStyle.FillPattern = FillPatternType.SOLID_FOREGROUND;//.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellA1.CellStyle = cellStyle;

            ICell cellB1 = row1.CreateCell((short)1);
            cellB1.SetCellValue("Goodbye");
            cellStyle = workbook.CreateCellStyle();
            cellStyle.FillForegroundColor = HSSFColor.LIGHT_CORNFLOWER_BLUE.index;
            cellStyle.FillPattern = FillPatternType.SOLID_FOREGROUND;
            cellB1.CellStyle = cellStyle;

            var cellC1 = row1.CreateCell((short)2);
            cellC1.SetCellValue(true);

            var cellD1 = row1.CreateCell((short)3);
            cellD1.SetCellValue(new DateTime());
            cellStyle = workbook.CreateCellStyle();
            cellStyle.DataFormat = HSSFDataFormat
                    .GetBuiltinFormat("m/d/yy h:mm");
            cellD1.CellStyle = cellStyle;

            workbook.Write(fileOut);
        }

Ref: Creating Excel spreadsheets .XLS and .XLSX in C# by Leniel Macaferi .

问题回答

另一种做法是导出 CSV (comma 分隔值) 文件, 这些文件只是带有数据的纯文本文件。 Excel 如果安装了, 通常是 CSV 文件的默认应用程序, 您不需要第三方库 。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签