NPOI实现excel的读取与写入

NPOI简介

NPOI可以在没有安装Office的情况下对Word或Excel文档进行读写操作。
NPOI是一个开源的C#读写Excel、WORD等微软OLE2组件文档的项目。

安装

NuGet管理工具中搜索NPOI,进行安装


NPOI安装

读取excel数据

/// 
/// Excel转换成DataTable(.xls)
/// 
/// Excel文件路径
/// 
public static DataTable ExcelToDataTable(string filePath)
{
    var dt = new DataTable();
    using (var file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    {
        var hssfworkbook = new HSSFWorkbook(file);
        var sheet = hssfworkbook.GetSheetAt(0);
        for (var j = 0; j < 5; j++)
        {
            dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString());
        }
        var rows = sheet.GetRowEnumerator();
        while (rows.MoveNext())
        {
            var row = (HSSFRow)rows.Current;
            var dr = dt.NewRow();
            for (var i = 0; i < row.LastCellNum; i++)
            {
                var cell = row.GetCell(i);
                if (cell == null)
                {
                    dr[i] = null;
                }
                else
                {
                    switch (cell.CellType)
                    {
                        case CellType.Blank:
                            dr[i] = "[null]";
                            break;
                        case CellType.Boolean:
                            dr[i] = cell.BooleanCellValue;
                            break;
                        case CellType.Numeric:
                            dr[i] = cell.ToString();
                            break;
                        case CellType.String:
                            dr[i] = cell.StringCellValue;
                            break;
                        case CellType.Formula:
                            try
                            {
                                dr[i] = cell.NumericCellValue;
                            }
                            catch
                            {
                                dr[i] = cell.StringCellValue;
                            }
                            break;
                        case CellType.Error:
                            break;
                        default:
                            dr[i] = "=" + cell.CellFormula;
                            break;
                    }
                }
            }
            dt.Rows.Add(dr);
        }
    }
    return dt;
}

写入excle

var workBook = new HSSFWorkbook();
ISheet sheet = null;
ICellStyle style = null;
style = workBook.CreateCellStyle();
//设置左对齐
style.Alignment = HorizontalAlignment.Left;
//style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
//style.BorderTop = BorderStyle.Thin;
style.BorderBottom = BorderStyle.Thin;


sheet = workBook.CreateSheet("sheet1");//创建表格

IRow row = sheet.CreateRow(0);
row.CreateCell(0).SetCellValue("序号");
row.GetCell(0).CellStyle = style;
row.CreateCell(1).SetCellValue("姓名");
row.GetCell(1).CellStyle = style;
        

workBook.SetActiveSheet(0);//设置默认表格
string filePath=@"c:\test.xls";
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
    workBook.Write(fs);
}            

写入已有的excel

/// 
/// 向已存在的excel写入数据
/// 
/// excel路径
/// 开始行索引
/// 列索引<列索引,单元格值>
public void addExcelData(string excelPath, int rowIndex, IDictionary cellData)
{
    FileStream fs = new FileStream(excelPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//读取流
    POIFSFileSystem ps = new POIFSFileSystem(fs);
    HSSFWorkbook workbook = new HSSFWorkbook(ps);
    ISheet sheet = workbook.GetSheetAt(0);//获取工作表

    //设置列宽
    SetColumnWidth(sheet, 0, 20);
    SetColumnWidth(sheet, 1, 10);
    //IRow row = sheet.GetRow(rowIndex); //获得已有的行
    IRow row = sheet.CreateRow(rowIndex); //创建新行


    ICell cell = null;
    ICellStyle style = null;
    foreach (KeyValuePair keyValue in cellData)
    {
        if (keyValue.Key == 1)
        {
            cell = row.CreateCell(keyValue.Key);
            cell.SetCellValue(keyValue.Value);
           
            style = workbook.CreateCellStyle();
            //设置左对齐
            style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.LEFT;
            //设置边框
            style.BorderLeft = BorderStyle.Thin;
            style.BorderRight = BorderStyle.Thin;
            style.BorderTop = BorderStyle.Thin;
            style.BorderBottom = BorderStyle.Thin;
            //设置填充色
            styleN.FillForegroundColor = IndexedColors.Red.Index;
            styleN.FillPattern = FillPattern.SolidForeground;
            //设置换行(若要单元格内换行必须加下面一句)
            style.WrapText = true;
            cell.CellStyle = style;
        }
        else
        {
            cell = row.CreateCell(keyValue.Key);
            cell.SetCellValue(keyValue.Value);

            //设置居中
            style = workbook.CreateCellStyle();
            style.VerticalAlignment = VerticalAlignment.CENTER;
            style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
            //设置边框
            style.BorderLeft = BorderStyle.Thin;
            style.BorderRight = BorderStyle.Thin;
            style.BorderTop = BorderStyle.Thin;
            style.BorderBottom = BorderStyle.Thin;
            cell.CellStyle = style;
        }
    }

    FileStream fout = new FileStream(excelPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);//写入流
    fout.Flush();
    workbook.Write(fout);//写入文件
    workbook = null;
    fout.Close();
}

你可能感兴趣的:(NPOI实现excel的读取与写入)