EPPlus 읽기 및 쓰기 Excel

29293 단어 .NET
Excel 읽기 및 쓰기 클래스ImportExportHelper
using OfficeOpenXml;
using System.Data;
using System.IO;

namespace Test
{
    public class ImportExportHelper
    {
        /// 
        /// 
        ///  Excel(EPPlus .xlsx)
        /// 
        /// 
        /// 
        public static DataSet ImportExcel(Stream stream)
        {
            DataSet ds = new DataSet();
            using (ExcelPackage package = new ExcelPackage(stream))
            {
                for (int i = 1; i <= package.Workbook.Worksheets.Count; i++)
                {
                    using (ExcelWorksheet worksheet = package.Workbook.Worksheets[i])
                    {
                        if (worksheet.Dimension == null)
                        {
                            continue;
                        }
                        DataTable table = new DataTable(worksheet.Name);
                        for (int rowNum = 1; rowNum <= worksheet.Dimension.End.Row; rowNum++)
                        {

                            #region  
                            if (table.Columns.Count == 0)
                            {
                                #region  
                                for (int columnNum = 1; columnNum <= worksheet.Dimension.End.Column; columnNum++)
                                {
                                    table.Columns.Add(worksheet.Cells[rowNum, columnNum].Value.ToString().Trim(), typeof(string));
                                }
                                continue;
                                #endregion
                            }
                            #endregion

                            #region  
                            DataRow dr = table.NewRow();
                            for (int columnNum = 1; columnNum <= table.Columns.Count; columnNum++)
                            {
                                dr[columnNum - 1] = worksheet.Cells[rowNum, columnNum].Value.ToString().Trim();
                            }
                            table.Rows.Add(dr);
                            #endregion
                        }
                        if (table.Rows.Count >= 1)
                        {
                            ds.Tables.Add(table);
                        }
                    }
                }
            }
            return ds;
        }

        /// 
        ///  Excel(EPPlus .xlsx)
        /// 
        /// 
        /// 
        public static byte[] ExportExcel(DataSet dataSet)
        {
            if (dataSet == null || dataSet.Tables.Count == 0)
            {
                return null;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                using (ExcelPackage package = new ExcelPackage(ms))
                {
                    for (int k = 0; k < dataSet.Tables.Count; k++)
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet" + (k + 1));
                        worksheet.Cells["A1"].LoadFromDataTable(dataSet.Tables[k], true);
                    }
                    package.Save();
                }
                return ms.ToArray();
            }
        }
    }
}

案例代码:
页面代码

<form id="form1" runat="server" >
    <asp:FileUpload ID="fileUpload" runat="server" AllowMultiple="false" />
    <asp:Button ID="btnUpload" runat="server" Text=" " OnClick="btnUpload_Click" />
    <asp:Button ID="btnExport" runat="server" Text=" " OnClick="btnExport_Click" />
</form>

백그라운드 코드/// /// /// /// /// protected void btnUpload_Click(object sender, EventArgs e) { if (!fileUpload.HasFile) { return; } string extension = Path.GetExtension(fileUpload.FileName); if ( extension != ".xlsx") { Response.Write(" .xlsx Excel"); return; } HttpPostedFile file = fileUpload.PostedFile; DataSet ds = ImportExportHelper.ImportExcel(file.InputStream); } /// /// /// /// /// protected void btnExport_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Age", typeof(int)); for (int i = 0; i < 2000; i++) { dt.Rows.Add("Test" + i, i); } DataTable dt2 = new DataTable(); dt2.Columns.Add("Subject", typeof(string)); dt2.Columns.Add("Score", typeof(int)); for (int i = 0; i < 200; i++) { dt2.Rows.Add("Subject" + i, 100); } DataSet ds = new DataSet(); ds.Tables.Add(dt); ds.Tables.Add(dt2); string fileName = " .xlsx"; Response.Clear(); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName)); Response.BinaryWrite(ImportExportHelper.ExportExcel(ds)); Response.Flush(); Response.End(); }

좋은 웹페이지 즐겨찾기