export Excel to DataTable using NPOI

后端 未结 11 1259
别那么骄傲
别那么骄傲 2021-02-19 03:22

I want to read Excel Tables 2010 xlsx using NPOI and then export data to DataTables but don\'t know how to use it. Can anyone show me step by step how to export Excel to Datatab

11条回答
  •  再見小時候
    2021-02-19 03:52

    I know I am a little late here but I think it may help others

    I have developed an excel utility with the use of the NPOI package, which can

    1. Simply takes your data table or the collection
    2. And Returns you excel while maintaining all the data table/list data type intact in the excel.

    Github Code repo.: https://github.com/ansaridawood/.NET-Generic-Excel-Export-Sample/tree/master/GenericExcelExport/ExcelExport

    Looking for a code explanation, you can find it here: https://www.codeproject.com/Articles/1241654/Export-to-Excel-using-NPOI-Csharp-and-WEB-API

    It uses NPOI DLL and it has 2 cs files to include and then you are good to go

    Below is the first file for reference AbstractDataExport.cs:

    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    
    namespace GenericExcelExport.ExcelExport
    {
        public interface IAbstractDataExport
        {
            HttpResponseMessage Export(List exportData, string fileName, string sheetName);
        }
    
        public abstract class AbstractDataExport : IAbstractDataExport
        {
            protected string _sheetName;
            protected string _fileName;
            protected List _headers;
            protected List _type;
            protected IWorkbook _workbook;
            protected ISheet _sheet;
            private const string DefaultSheetName = "Sheet1";
    
            public HttpResponseMessage Export
                  (List exportData, string fileName, string sheetName = DefaultSheetName)
            {
                _fileName = fileName;
                _sheetName = sheetName;
    
                _workbook = new XSSFWorkbook(); //Creating New Excel object
                _sheet = _workbook.CreateSheet(_sheetName); //Creating New Excel Sheet object
    
                var headerStyle = _workbook.CreateCellStyle(); //Formatting
                var headerFont = _workbook.CreateFont();
                headerFont.IsBold = true;
                headerStyle.SetFont(headerFont);
    
                WriteData(exportData); //your list object to NPOI excel conversion happens here
    
                //Header
                var header = _sheet.CreateRow(0);
                for (var i = 0; i < _headers.Count; i++)
                {
                    var cell = header.CreateCell(i);
                    cell.SetCellValue(_headers[i]);
                    cell.CellStyle = headerStyle;
                }
    
                for (var i = 0; i < _headers.Count; i++)
                {
                    _sheet.AutoSizeColumn(i);
                }
    
                using (var memoryStream = new MemoryStream()) //creating memoryStream
                {
                    _workbook.Write(memoryStream);
                    var response = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ByteArrayContent(memoryStream.ToArray())
                    };
    
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue
                           ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                    response.Content.Headers.ContentDisposition = 
                           new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = $"{_fileName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"
                    };
    
                    return response;
                }
            }
    
            //Generic Definition to handle all types of List
            public abstract void WriteData(List exportData);
        }
    }
    

    and this the second and final file AbstractDataExportBridge.cs:

    using NPOI.SS.UserModel;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Text.RegularExpressions;
    
    namespace GenericExcelExport.ExcelExport
    {
        public class AbstractDataExportBridge : AbstractDataExport
        {
            public AbstractDataExportBridge()
            {
                _headers = new List();
                _type = new List();
            }
    
            public override void WriteData(List exportData)
            {
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
    
                DataTable table = new DataTable();
    
                foreach (PropertyDescriptor prop in properties)
                {
                    var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                    _type.Add(type.Name);
                    table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? 
                                      prop.PropertyType);
                    string name = Regex.Replace(prop.Name, "([A-Z])", " $1").Trim(); //space separated 
                                                                               //name by caps for header
                    _headers.Add(name);
                }
    
                foreach (T item in exportData)
                {
                    DataRow row = table.NewRow();
                    foreach (PropertyDescriptor prop in properties)
                        row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                    table.Rows.Add(row);
                }
    
                IRow sheetRow = null;
    
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    sheetRow = _sheet.CreateRow(i + 1);
                    for (int j = 0; j < table.Columns.Count; j++)
                    {
                        ICell Row1 = sheetRow.CreateCell(j);
    
                        string type = _type[j].ToLower();
                        var currentCellValue = table.Rows[i][j];
    
                        if (currentCellValue != null && 
                            !string.IsNullOrEmpty(Convert.ToString(currentCellValue)))
                        {
                            if (type == "string")
                            {
                                Row1.SetCellValue(Convert.ToString(currentCellValue));
                            }
                            else if (type == "int32")
                            {
                                Row1.SetCellValue(Convert.ToInt32(currentCellValue));
                            }
                            else if (type == "double")
                            {
                                Row1.SetCellValue(Convert.ToDouble(currentCellValue));
                            }
                        }
                        else
                        {
                            Row1.SetCellValue(string.Empty);
                        }
                    }
                }
            }
        }
    }
    

    For a detailed explanation, refer link provided in the beginning.

提交回复
热议问题