簡體   English   中英

如何使用epplus從datagrid保存Excel?

[英]how can I save the excel from datagrid using epplus?

void Export()
    {
        string filePath = "";
        SaveFileDialog dialog = new SaveFileDialog();
        dialog.Filter = "Excel | *.xlsx | Excel 2003 | *.xls";
        if (dialog.ShowDialog() == true)
        {
            filePath = dialog.FileName;
        }
        if (string.IsNullOrEmpty(filePath))
        {
            MessageBox.Show("Link is not valid");
            return;
        }           
        DataTable dt = new DataTable();
        dtgExcel.DataContext = dt;
        using (ExcelPackage excel = new ExcelPackage())
        {
            var ws = excel.Workbook.Worksheets.Add("Sheet1");
            ws.Cells[1,1].LoadFromDataTable(dt, true);
            ws.Cells.AutoFitColumns();
            using (ExcelRange objRange = ws.Cells["A1:XFD1"])
            {
                objRange.Style.Font.Bold = true;
                objRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                objRange.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                objRange.Style.Fill.PatternType = ExcelFillStyle.Solid;            objRange.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#B7DEE8"));
            }
            FileStream file = File.Create(filePath);
            file.Close();
            File.WriteAllBytes(filePath, excel.GetAsByteArray());
        }
        MessageBox.Show("It's successful!!");               
    }

我使用按鈕進行此事件,它返回到“ System.ArgumentException:'列超出范圍'”可以為我解決此問題嗎? 非常感謝。

我認為它必須與您傳遞的dataTable有關。 您使用的數據是什么樣的?

以下示例同時使用ws.Cells[1,1] or ws.Cells["A1"]

 class Program
{
    static void Main(string[] args)
    {
        ExcelPackage p = new ExcelPackage();
        try
        {
            p = new ExcelPackage();
        }
        catch (System.IO.IOException fex)
        {
            //file is open
            Console.WriteLine("Can not process while file is open.Please close file and try again.");
            return;
        }
        catch (System.IO.InvalidDataException lex)
        {
            //invalid file type
            Console.WriteLine("Invalid File Type. Please Try Again.");
            return;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Unhandled Exception. Please Contact Developer.");
            return;
        }

        var wb = p.Workbook;            

        //create table
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("Col1"));
        dt.Columns.Add(new DataColumn("Col2"));
        dt.Columns.Add(new DataColumn("Col3"));
        dt.Columns.Add(new DataColumn("Col4"));
        dt.Columns.Add(new DataColumn("Col5"));

        //fill table
        DataRow workRow;
        for (int i = 0; i <= 9; i++)
        {
            workRow = dt.NewRow();
            workRow["Col1"] = string.Format("Row {0} Col 1", i);
            workRow["Col2"] = string.Format("Row {0} Col 2", i);
            workRow["Col3"] = string.Format("Row {0} Col 3", i);
            workRow["Col4"] = string.Format("Row {0} Col 4", i);
            workRow["Col5"] = string.Format("Row {0} Col 5", i);
            dt.Rows.Add(workRow);
        }

        //create worksheet
        var ws = wb.Worksheets.Add("Foo");

        //load data into cell A1            
        ws.Cells["A1"].LoadFromDataTable(dt, true);
        ws.Cells.AutoFitColumns();
        using (ExcelRange objRange = ws.Cells["A1:XFD1"])
        {
            objRange.Style.Font.Bold = true;
            objRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            objRange.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
            objRange.Style.Fill.PatternType = ExcelFillStyle.Solid;
            objRange.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#B7DEE8"));
        }
        p.SaveAs(new FileInfo(@"C:\FooFolder\Foo.xlsx"));

        Console.WriteLine("It's Successful");
    }              
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM