C#使用NPOI 操作excel

DataTable导入导出

请自行添加以下动态库引用

NPOI.dll

NPOI.OOXML.dll

NPOI.OpenXml4Net.dll

NPOI.OpenXmlFormats.dll

using System;
using System.Data;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace ExcelHelper
{
    class ExcelHelper
    {

        public static void WriteToExcel(DataTable dt, string filePathAndName, string sheetname)
        {
            if (!string.IsNullOrEmpty(filePathAndName) && null != dt && dt.Rows.Count > 0)
            {
                XSSFWorkbook book = new XSSFWorkbook();
                ISheet sheet = book.CreateSheet(sheetname);
                ICellStyle styleone = book.CreateCellStyle();
                IFont font1 = book.CreateFont();
                font1.Color = 255;//颜色:色
                font1.FontHeightInPoints = 14;
                styleone.SetFont(font1);
                HSSFColor hssfcolor = new HSSFColor();
                styleone.FillBackgroundColor = 22;
                for (int i = 0; i < dt.Columns.Count; i++)
                    sheet.SetColumnWidth(i, 25 * 256);                       //设置列宽

                IRow row = sheet.CreateRow(0);
                row.Height = 100 * 5;
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName); //列名
                    sheet.GetRow(0).GetCell(i).CellStyle = styleone;
                }
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    IRow row2 = sheet.CreateRow(i + 1);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        row2.CreateCell(j).SetCellValue(Convert.ToString(dt.Rows[i][j]));
                    }
                }
                using (MemoryStream ms = new MemoryStream())
                {
                    book.Write(ms);
                    using (FileStream fs = new FileStream(filePathAndName, FileMode.Create, FileAccess.Write))
                    {
                        byte[] data = ms.ToArray();
                        fs.Write(data, 0, data.Length);
                        fs.Flush();
                    }
                    book = null;
                }
            }
        }

        public static DataTable ReadExcel(string filePath, bool ToLower = false)//Excel内容读出到DataTable,excel每行每列单元格需整齐
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return null;
            }
            IWorkbook hssfworkbook;
            if (filePath.Contains(".xlsx"))
            {
                using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    hssfworkbook = new XSSFWorkbook(file);
                }

            }
            else
            {
                using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    hssfworkbook = new HSSFWorkbook(file);
                }
            }

            ISheet sheet = hssfworkbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
            DataTable dt = new DataTable();
            int idx = 0;
            while (idx < 3)
            {
                try
                {
                    int count = sheet.GetRow(idx).LastCellNum;
                    for (int j = 0; j < count; j++)
                    {
                        string col = sheet.GetRow(idx).Cells[j].ToString().Trim();
                        if (ToLower)
                            col = col.ToLower();
                        dt.Columns.Add(col);
                        dt.Columns[j].ColumnName = col;
                    }
                    break;
                }
                catch { }
                idx++;
                rows.MoveNext();
            }
            while (rows.MoveNext())
            {
                IRow row;
                if (filePath.Contains(".xlsx"))
                {
                    row = (XSSFRow)rows.Current;
                }
                else
                {
                    row = (HSSFRow)rows.Current;
                }

                DataRow dr = dt.NewRow();
                for (int i = 0; i < row.LastCellNum; i++)
                {
                    ICell cell = row.GetCell(i);
                    if (cell == null)
                    {
                        dr[i] = "";
                    }
                    else
                    {
                        dr[i] = cell;
                    }
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@David Liu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值