码迷,mamicode.com
首页 > Windows程序 > 详细

C#导入导出数据你该知道的方法。

时间:2015-11-17 18:30:13      阅读:301      评论:0      收藏:0      [点我收藏+]

标签:

 导入数据

技术分享
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Common
{
    public static class Import
    {
        /// <summary>
        /// 获取导入的Excel的列名(第一行Titile)
        /// </summary>
        /// <returns></returns>
        public static List<string> GetFieldNames(string filePath)
        {
            ISheet sheet = GetSheet(filePath);
            List<string> filedNameList = new List<string>();
            try
            {
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                    {
                        ICell cell = firstRow.GetCell(i);
                        if (cell != null)
                        {
                            string cellValue = cell.StringCellValue;
                            if (cellValue != null)
                            {
                                filedNameList.Add(cellValue);
                            }
                        }
                    }
                }


            }
            catch (Exception ex)
            {
                throw ex;
            }
            return filedNameList;

        }
        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public static DataTable ExcelToDataTable(string filePath)
        {
            ISheet sheet = GetSheet(filePath);
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                    {
                        ICell cell = firstRow.GetCell(i);
                        if (cell != null)
                        {
                            string cellValue = cell.StringCellValue;
                            if (cellValue != null)
                            {
                                DataColumn column = new DataColumn(cellValue);
                                data.Columns.Add(column);
                            }
                        }
                    }
                    startRow = sheet.FirstRowNum + 1;


                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null       

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                                dataRow[j] = row.GetCell(j).ToString();
                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取sheet
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private static ISheet GetSheet(string filePath)
        {
            ISheet sheet = null;
            MemoryStream memoryStream = CommonHelper.ReadFile(filePath);
            memoryStream.Position = 0;
            try
            {
                IWorkbook workbook = null;
                if (filePath.IndexOf(".xlsx") > 0) // 2007版本
                {
                    workbook = new XSSFWorkbook(memoryStream);
                }
                else if (filePath.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(memoryStream);
                memoryStream.Close();
                memoryStream.Dispose();

                sheet = workbook.GetSheetAt(0);
                return sheet;
            }
            catch (Exception ex)
            {
                memoryStream.Close();
                memoryStream.Dispose();
                throw ex;
            }
        }
    }
}
View Code

 

 

 导出数据

技术分享
using CRM.Models.Base;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;



namespace  Common.Utils
{
    public class Export
    {
        public static byte[] ExportToExcel<T>(List<T> modelList)
        {
            byte[] resultByte = null;

            IWorkbook workbook = new HSSFWorkbook();//创建Workbook对象
            ISheet sheet = workbook.CreateSheet();

            //填充表头
            IRow dataRow = sheet.CreateRow(0);
            System.Reflection.PropertyInfo[] ps = typeof(T).GetProperties();
            for (int i = 0; i < ps.Count(); i++)
            {
                //object obj = ps[i].GetValue(typeof(T), null);
                string name = ps[i].Name;
                dataRow.CreateCell(i).SetCellValue(name);
            }

            //填充内容
            for (int i = 0; i < modelList.Count; i++)
            {
                dataRow = sheet.CreateRow(i + 1);
                var type = modelList[i].GetType();
                ps = type.GetProperties();
                for (int j = 0; j < ps.Count(); j++)
                {
                    object obj = ps[j].GetValue(modelList[i], null);
                    if (obj != null)
                        dataRow.CreateCell(j).SetCellValue(obj.ToString());
                }
            }


            //保存
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                resultByte = ms.ToArray();
                ms.Dispose();
            }

            return resultByte;
        }

        /// <summary>
        /// 根据DateTable导出Excel
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static byte[] ExportToExcel(DataTable dt)
        {
            byte[] resultByte = null;

            IWorkbook workbook = new HSSFWorkbook();//创建Workbook对象
            ISheet sheet = workbook.CreateSheet();

            //填充表头
            IRow dataRow = sheet.CreateRow(0);

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                string name = dt.Columns[i].ColumnName;
                dataRow.CreateCell(i).SetCellValue(name);
            }

            //填充内容
            for (int i = 0; i < dt.Rows.Count; i++)
            {
              
                dataRow = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    object obj = dt.Rows[i][j];
                    if (obj != null)
                    { 
                        dataRow.CreateCell(j).SetCellValue(obj.ToString()); 
                    }
                }
            }


            //保存
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                resultByte = ms.ToArray();
                ms.Dispose();
            }

            return resultByte;
        }
    }
}
View Code

 

C#导入导出数据你该知道的方法。

标签:

原文地址:http://www.cnblogs.com/sunnie/p/4972389.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!