C#端excel和csv文件导入成datatable

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
using System.Data;
using System.Web;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {


        static void Main(string[] args)
        {
            string fileName = "C:\\Users\\hankham\\Desktop\\临时文件\\2018年度需求清单20171227-风险.xlsx";
            DataTable dt = GetDataTable(fileName);
            int row = dt.Rows.Count;
            int columns = dt.Columns.Count;
            Console.WriteLine(row);
            Console.WriteLine(columns);
            Console.WriteLine(dt.Rows[7380][8].ToString());

            //string fileName = "C:\\Users\\hankham\\Desktop\\临时文件\\新建文件夹\\行情文件\\cmcMarketValue_bond.csv";
            //Program pr = new Program();
            //DataTable dt = pr.ImportCsvToDataTable(fileName);
            //int row = dt.Rows.Count;
            //int columns = dt.Columns.Count;
            //Console.WriteLine(row);
            //Console.WriteLine(columns);
            //Console.WriteLine(columns);
            //Console.WriteLine(dt.Rows[8][8].ToString());
        }

        public static DataTable GetDataTable(string filepath)
        {
            var dt = new DataTable("xls");
            if (filepath.Last() == 's')
            {
                dt = ImportExcelFileOld(filepath);
            }
            else
            {
                dt = ImportExcelFileNew(filepath);
            }
            return dt;
        }


        public static DataTable ImportExcelFileOld(string filePath)
        {
            try
            {
                FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
                ISheet sheet = hssfworkbook.GetSheetAt(0);

                IEnumerator rows = sheet.GetRowEnumerator();
                DataTable dt = new DataTable();
                int num = sheet.GetRow(0).LastCellNum;
                for (int j = 0; j < num; j++)
                {
                    dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString());
                }
                while (rows.MoveNext())
                {
                    HSSFRow row = (HSSFRow)rows.Current;
                    DataRow dr = dt.NewRow();
                    if (num < row.LastCellNum)
                    {
                        throw new Exception("最大列数不能大于表格起始列数");
                    }
                    for (int i = 0; i < row.LastCellNum; i++)
                    {
                        ICell cell = row.GetCell(i);
                        if (cell == null)
                        {
                            dr[i] = null;
                        }
                        else
                        {
                            dr[i] = cell.ToString();
                        }
                    }
                    dt.Rows.Add(dr);
                }
                return dt;

            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public static DataTable ImportExcelFileNew(string filePath)
        {
            try
            {
                FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                XSSFWorkbook xssfworkbook = new XSSFWorkbook(file);
                ISheet sheet = xssfworkbook.GetSheetAt(0);
                IEnumerator rows = sheet.GetRowEnumerator();
                DataTable dt = new DataTable();
                int num = sheet.GetRow(0).LastCellNum;
                for (int j = 0; j < num; j++)
                {
                    dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString());
                }
                while (rows.MoveNext())
                {
                    XSSFRow row = (XSSFRow)rows.Current;
                    DataRow dr = dt.NewRow();
                    if (num < row.LastCellNum)
                    {
                        throw new Exception("最大列数不能大于表格起始列数");
                    }
                    for (int i = 0; i < row.LastCellNum; i++)
                    {
                        ICell cell = row.GetCell(i);
                        if (cell == null)
                        {
                            dr[i] = null;
                        }
                        else
                        {
                            dr[i] = cell.ToString();
                        }
                    }
                    dt.Rows.Add(dr);
                }
                return dt;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// Stream读取.csv文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public DataTable ImportCsvToDataTable(string filePath)
        {
            FileStream fs = null;
            StreamReader sr = null;
            try
            {
                DataTable dt = new DataTable();
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                sr = new StreamReader(fs, System.Text.Encoding.Default);
                //记录每次读取的一行记录
                string strLine = "";
                //记录每行记录中的各字段内容
                string[] aryLine;
                //标示列数
                int columnCount = 0;
                int firstCount = 0;
                Boolean first = true;
                //逐行读取CSV中的数据
                while ((strLine = sr.ReadLine()) != null)
                {
                    aryLine = strLine.Split(',');

                    columnCount = aryLine.Length;                    
                    if (first)
                    {
                        for (int j = 0; j < columnCount; j++)
                        {
                            dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString());
                        }
                        first = false;
                        firstCount = columnCount;
                    }
                    else
                    {
                        DataRow dr = dt.NewRow();
                        if (firstCount < columnCount)
                        {
                            throw new Exception("最大列数不能大于表格起始列数");
                        }
                        for (int j = 0; j < columnCount - 1; j++)
                        {
                            string str = aryLine[j];
                            dr[j] = str;
                        }
                        dt.Rows.Add(dr);
                    }


                }
                return dt;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                sr.Close();
                fs.Close();
            }
        }



    }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值