c#NPOI 导入导出 excel

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;


namespace LabSampleAnalysis
{
     public partial class Form1 : Form
    {
      DataSet ds = new DataSet();
    public Form1()
    {
        InitializeComponent();
    }
    /// <summary>
    /// 初始化加载
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>

    private void Form1_Load(object sender, EventArgs e)
    {
        //this.dataGridView1.DataSource = ds.Tables[0];
        
    }
    /// <summary>
    /// 导入
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button1_Click(object sender, EventArgs e)
    {
        //定义一个数据集接受导入进来的数据
        IWorkbook book = null;
        DataTable dt = null;
        OpenFileDialog od = new OpenFileDialog();//提示用户打开文件
        od.Filter = "Excel(*.xls)|*.xls|Excel(*.xlsx)|*.xlsx|全部文件(*.*)|*.*";
       
        if (od.ShowDialog()==System.Windows.Forms.DialogResult.Cancel)
        {
            return;
        }
        string strPath = od.FileName;
        string fileType = System.IO.Path.GetExtension(strPath);//获取文件的后缀
        //打开文件流
        FileStream fs = new FileStream(od.FileName,FileMode.Open,FileAccess.Read);
        if (fileType == ".xls")
        {
            //把文件流传到工作簿中
            book = new HSSFWorkbook(fs);
         }
        else if (fileType == ".xlsx")
          {
            book = new XSSFWorkbook(fs);
         }
        else
        {
            MessageBox.Show("请选择execel文件!","提示");
            return;
        }
        //获得工作簿中sheet表的个数
            int sheetcout = book.NumberOfSheets;
        //循环遍历工作簿
            for (int sheetindex = 0; sheetindex < sheetcout; sheetindex++)
            {
            //拿到对应序号的sheet表
                ISheet sheet = book.GetSheetAt(sheetindex);
                if (sheet == null)
                {
                    continue;
                }
                //获得第一行数据,及表头
                IRow row = sheet.GetRow(0);
                if (row == null) continue;
                //获得第一行第一个单元格的索引
                int firstcellnum = row.FirstCellNum;
               //获得第一行最后一个单元格的索引
                int lastcellnum = row.LastCellNum;
                if (firstcellnum == lastcellnum) continue;
                dt = new DataTable(sheet.SheetName);
                for (int i = firstcellnum; i < lastcellnum; i++)
                {
                //给datatable加入列
                    dt.Columns.Add(row.GetCell(i).StringCellValue, typeof(string));
                }
                for (int i = 1; i <=sheet.LastRowNum; i++)
                {
                    DataRow newdatarow = dt.Rows.Add();
                    for (int j = firstcellnum; j < lastcellnum; j++)
                    {
                     //给table单元格赋值
                        newdatarow[j] = sheet.GetRow(i).GetCell(j).StringCellValue.ToString();
                    }
                }
                ds.Tables.Add(dt);
            }
            this.dataGridView1.DataSource = ds.Tables[0];
        


    }
    /// <summary>
    /// 导出
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button2_Click(object sender, EventArgs e)
    {
        IWorkbook book = null;
        SaveFileDialog sf = new SaveFileDialog();
        sf.Filter = "Excel(*.xls)|*.xls|Excel(*.xlsx)|*.xlsx";
        if(sf.ShowDialog()==System.Windows.Forms.DialogResult.Cancel)
        {
            return;
        }
        string name = sf.FileName;
        string name1 = System.IO.Path.GetExtension(name);
        if(name1=="xls")
        {
            book = new HSSFWorkbook();
        }
        else
        {
            book = new XSSFWorkbook();
        }
        ISheet sheet = book.CreateSheet("sheet1");
        //添加表头
        IRow row = sheet.CreateRow(0);
        int index = 0;
        foreach (DataGridViewColumn item in this.dataGridView1.Columns)
        {
            if(item.Visible)
            {
                ICell cell = row.CreateCell(index);
                cell.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell.SetCellValue(item.HeaderText);
                index++;
            }
        }
        //添加数据
        for(int i=0;i<this.dataGridView1.RowCount-1;i++)
        {
            index = 0;
         
            row = sheet.CreateRow(i+1);
            foreach (DataGridViewColumn item in this.dataGridView1.Columns)
            {
                if (item.Visible)
                { 
                    ICell cell = row.CreateCell(index);//第一列,第一个单元格。
                    cell.SetCellType(NPOI.SS.UserModel.CellType.String);
                    string nam1e = this.dataGridView1[index,i].Value.ToString();//col,row
                    cell.SetCellValue(nam1e);
               
                    index++;
                }
            }
        }
        //写入(创建其支持存储区的内存流)
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        book.Write(ms);//把工作簿写到内存流中
        book = null;
        using (FileStream fs=new FileStream(sf.FileName,FileMode.Create,FileAccess.Write))
        {
            byte[] data = ms.ToArray();//将文件流写入到字节数组
            fs.Write(data,0,data.Length);//将字节块写入到文件流
            fs.Flush();//清除此流的缓冲区,使得所有缓冲数据都写入到文件中。
            MessageBox.Show("导出成功!");
        }
        ms.Close();//关闭当前流并释放与之关联的资源
        ms.Dispose();//释放由stream使用的所有资源
    }


  
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用NPOI库在C#中实现导入导出Excel数据可以按照以下步骤进行: 1. 首先,确保已经将NPOI库添加到你的C#项目中。你可以通过NuGet包管理器搜索并安装"NPOI"来添加这个库。 2. 创建一个Excel文件并写入数据: ```csharp using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.IO; // 创建一个Workbook对象 IWorkbook workbook = new XSSFWorkbook(); // 创建一个Sheet对象 ISheet sheet = workbook.CreateSheet("Sheet1"); // 写入数据行 for (int i = 0; i < data.Count; i++) { IRow row = sheet.CreateRow(i); // 写入数据列 for (int j = 0; j < data[i].Count; j++) { row.CreateCell(j).SetCellValue(data[i][j]); } } // 保存文件 using (FileStream fileStream = new FileStream("path/to/excel.xlsx", FileMode.Create)) { workbook.Write(fileStream); } ``` 3. 从Excel文件读取数据: ```csharp using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.IO; // 打开Excel文件 using (FileStream fileStream = new FileStream("path/to/excel.xlsx", FileMode.Open, FileAccess.Read)) { IWorkbook workbook = new XSSFWorkbook(fileStream); // 获取第一个Sheet ISheet sheet = workbook.GetSheetAt(0); List<List<string>> data = new List<List<string>>(); // 遍历行 for (int i = 0; i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); List<string> rowData = new List<string>(); // 遍历列 for (int j = 0; j < row.LastCellNum; j++) { ICell cell = row.GetCell(j); rowData.Add(cell.ToString()); } data.Add(rowData); } // 处理读取到的数据 // ... } ``` 这是一个简单的示例,你可以根据自己的需求进行扩展和修改。记得替换代码中的文件路径为你的实际路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值