b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

C#使用NPOI库读写Excel文件设置公式使用

电脑杂谈  发布时间:2021-06-08 00:02:49  来源:网络整理

原文:C#使用NPOI库读写Excel文件

NPOI是开源POI项目的.NET版本,可用于读写Excel、Word、PPT文件。在处理Excel文件时,NPOI同时兼容xls和xlsx。官网提供了一个Examples列表,里面给出了很多应用场景的例子。打包好的二进制文件类库只有几MB,使用起来非常方便。

读取 Excel

NPOI 使用 HSSFWorkbook 类来处理 xls,使用 XSSFWorkbook 类来处理 xlsx。它们都继承了接口IWorkbook,所以可以通过IWorkbook统一处理xls和xlsx格式的文件。

下面是一个简单的例子

c#读写excel文件 npoi_c# datatable 写excel_c写xml文件

public void ReadFromExcelFile(string filePath)
{
    IWorkbook wk = null;
    string extension = System.IO.Path.GetExtension(filePath);
    try
    {
        FileStream fs = File.OpenRead(filePath);
        if (extension.Equals(".xls"))
        {
            //把xls文件中的数据写入wk中
            wk = new HSSFWorkbook(fs);
        }
        else
        {
            //把xlsx文件中的数据写入wk中
            wk = new XSSFWorkbook(fs);
        }
        fs.Close();
        //读取当前表数据
        ISheet sheet = wk.GetSheetAt(0);
        IRow row = sheet.GetRow(0);  //读取当前行数据
        //LastRowNum 是当前表的总行数-1(注意)
        int offset = 0;
        for (int i = 0; i <= sheet.LastRowNum; i++)
        {
            row = sheet.GetRow(i);  //读取当前行数据
            if (row != null)
            {
                //LastCellNum 是当前行的总列数
                for (int j = 0; j < row.LastCellNum; j++)
                {
                    //读取该行的第j列数据
                    string value = row.GetCell(j).ToString();
                    Console.Write(value.ToString() + " ");
                }
                Console.WriteLine("\n");
            }
        }
    }
    
    catch (Exception e)
    {
        //只在Debug模式下才输出
        Console.WriteLine(e.Message);
    }
}

Excel中的单元格有不同的数据格式,如数字、日期、字符串等,读取时可以根据不同的格式设置不同类型的对象,方便后面的数据处理。

//获取cell的数据,并设置为对应的数据类型
public object GetCellValue(ICell cell)
{
    object value = null;
    try
    {
        if (cell.CellType != CellType.Blank)
        {
            switch (cell.CellType)
            {
                case CellType.Numeric:
                    // Date comes here
                    if (DateUtil.IsCellDateFormatted(cell))
                    {
                        value = cell.DateCellValue;
                    }
                    else
                    {
                        // Numeric type
                        value = cell.NumericCellValue;
                    }
                    break;
                case CellType.Boolean:
                    // Boolean type
                    value = cell.BooleanCellValue;
                    break;
                case CellType.Formula:
                    value = cell.CellFormula;
                    break;
                default:
                    // String type
                    value = cell.StringCellValue;
                    break;
            }
        }
    }
    catch (Exception)
    {
        value = "";
    }
    return value;
}

特别注意CellType中没有Date,date类型的数据类型是Numeric。事实上,日期数据在Excel中也是以数字形式存储的。可以使用 DateUtil.IsCellDateFormatted 方法判断是否为日期类型。

c写xml文件_c# datatable 写excel_c#读写excel文件 npoi

使用GetCellValue方法,Excel写入数据时需要SetCellValue方法,缺少的类型可以自己补。

//根据数据类型设置不同类型的cell
public static void SetCellValue(ICell cell, object obj)
{
    if (obj.GetType() == typeof(int))
    {
        cell.SetCellValue((int)obj);
    }
    else if (obj.GetType() == typeof(double))
    {
        cell.SetCellValue((double)obj);
    }
    else if (obj.GetType() == typeof(IRichTextString))
    {
        cell.SetCellValue((IRichTextString)obj);
    }
    else if (obj.GetType() == typeof(string))
    {
        cell.SetCellValue(obj.ToString());
    }
    else if (obj.GetType() == typeof(DateTime))
    {
        cell.SetCellValue((DateTime)obj);
    }
    else if (obj.GetType() == typeof(bool))
    {
        cell.SetCellValue((bool)obj);
    }
    else
    {
        cell.SetCellValue(obj.ToString());
    }
}

cell.SetCellValue()方法只有四个重载方法,参数分别是string、bool、DateTime、double、IRichTextString

使用cell.SetCellFormula(字符串公式)设置公式

写Excel

下面是一个简单的例子。更多信息请参考官网提供的示例。

public void WriteToExcel(string filePath)
{
    //创建工作薄  
    IWorkbook wb;
    string extension = System.IO.Path.GetExtension(filePath);
    //根据指定的文件格式创建对应的类
    if (extension.Equals(".xls"))
    {
        wb = new HSSFWorkbook();
    }
    else
    {
        wb = new XSSFWorkbook();
    }
    ICellStyle style1 = wb.CreateCellStyle();//样式
    style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平对齐方式
    style1.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直对齐方式
    //设置边框
    style1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
    style1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
    style1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
    style1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
    style1.WrapText = true;//自动换行
    ICellStyle style2 = wb.CreateCellStyle();//样式
    IFont font1 = wb.CreateFont();//字体
    font1.FontName = "楷体";
    font1.Color = HSSFColor.Red.Index;//字体颜色
    font1.Boldweight = (short)FontBoldWeight.Normal;//字体加粗样式
    style2.SetFont(font1);//样式里的字体设置具体的字体样式
    //设置背景色
    style2.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
    style2.FillPattern = FillPattern.SolidForeground;
    style2.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
    style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平对齐方式
    style2.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直对齐方式
    ICellStyle dateStyle = wb.CreateCellStyle();//样式
    dateStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平对齐方式
    dateStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直对齐方式
    //设置数据显示格式
    IDataFormat dataFormatCustom = wb.CreateDataFormat();
    dateStyle.DataFormat = dataFormatCustom.GetFormat("yyyy-MM-dd HH:mm:ss");
    //创建一个表单
    ISheet sheet = wb.CreateSheet("Sheet0");
    //设置列宽
    int[] columnWidth = { 10, 10, 20, 10 };
    for (int i = 0; i < columnWidth.Length; i++)
    {
        //设置列宽度,256*字符数,因为单位是1/256个字符
        sheet.SetColumnWidth(i, 256 * columnWidth[i]);
    }
    //测试数据
    int rowCount = 3, columnCount = 4;
    object[,] data = {
        {"列0", "列1", "列2", "列3"},
        {"", 400, 5.2, 6.01},
        {"", true, "2014-07-02", DateTime.Now}
        //日期可以直接传字符串,NPOI会自动识别
        //如果是DateTime类型,则要设置CellStyle.DataFormat,否则会显示为数字
    };
    IRow row;
    ICell cell;
    
    for (int i = 0; i < rowCount; i++)
    {
        row = sheet.CreateRow(i);//创建第i行
        for (int j = 0; j < columnCount; j++)
        {
            cell = row.CreateCell(j);//创建第j列
            cell.CellStyle = j % 2 == 0 ? style1 : style2;
            //根据数据类型设置不同类型的cell
            object obj = data[i, j];
            SetCellValue(cell, data[i, j]);
            //如果是日期,则设置日期显示的格式
            if (obj.GetType() == typeof(DateTime))
            {
                cell.CellStyle = dateStyle;
            }
            //如果要根据内容自动调整列宽,需要先setCellValue再调用
            //sheet.AutoSizeColumn(j);
        }
    }
    //合并单元格,如果要合并的单元格中都有数据,只会保留左上角的
    //CellRangeAddress(0, 2, 0, 0),合并0-2行,0-0列的单元格
    CellRangeAddress region = new CellRangeAddress(0, 2, 0, 0);
    sheet.AddMergedRegion(region);
    try
    {
        FileStream fs = File.OpenWrite(filePath);
        wb.Write(fs);//向打开的这个Excel文件中写入表单并保存。  
        fs.Close();
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.Message);
    }
}

如果要将单元格设置为只读或可写,可以参考这里,方法如下:

ICellStyle unlocked = wb.CreateCellStyle();
unlocked.IsLocked = false;//设置该单元格为非锁定
cell.SetCellValue("未被锁定");
cell.CellStyle = unlocked;
...
//保护表单,password为解锁密码
//cell.CellStyle.IsLocked = true;的单元格将为只读
sheet.ProtectSheet("password");

cell.CellStyle.IsLocked 默认为 true,因此必须执行 sheet.ProtectSheet("password") 来锁定单元格。对于不想被锁定的单元格,必须在单元格的CellStyle中设置IsLocked = false


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/shumachanpin/article-381202-1.html

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      热点图片
      拼命载入中...