C# NPOI 写入EXCEL

本文详细介绍如何使用两种方法将字符串数组写入EXCEL文件,一种是通过COM自动化操作现有EXCEL文件,另一种是利用NPOI库创建新的EXCEL文件并进行数据填充。这两种方法为数据处理和报表生成提供了灵活的选择。
/// <summary>
/// 将字符串数组写入EXCEL
/// </summary>
/// <param name="xlFile">EXCEL文件</param>
/// <param name="sheetName">EXCEL表名称</param>
/// <param name="str">输出字符串数组</param>
/// <param name="startCell">EXCEL输出起始单元格地址,如A1</param>
/// <param name="endCell">EXCEL输出结束单元格地址,如B2</param>
/// <returns>true=输出EXCEL文件成功, false=输出EXCEL文件失败</returns>
public static bool WriteExcel(string xlFile, string sheetName, string[,] str, string startCell, string endCell)
{
    Excel.Application xlApp = null;
    Excel.Workbook xlBook = null;
    try
    {
        xlApp = new Excel.Application();
        xlApp.DisplayAlerts = false;
        xlBook = xlApp.Workbooks.Open(xlFile, Excel.XlUpdateLinks.xlUpdateLinksNever);
        Excel.Worksheet xlSheet = xlBook.Worksheets[sheetName] as Excel.Worksheet;

        //Excel.Worksheet xlSheet2 = xlBook.Worksheets.Add();
        //xlSheet.Copy(xlSheet2);


        if (xlSheet == null)
            return false;

        Excel.Range rng = xlSheet.get_Range(startCell, endCell);
        rng.set_Value(System.Reflection.Missing.Value, str);

        xlBook.Save();
    }
    catch (Exception ex)
    {
        Debug.WriteLine(string.Format("将字符串数组写入EXCEL出错:消息={0}, 堆栈={1}", ex.Message, ex.StackTrace));
        return false;
    }
    finally
    {
        if (xlBook != null)
        {
            xlBook.Close();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
        }
        if (xlApp != null)
        {
            xlApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
        }
    }

    return true;

}


/// <summary>
/// NPOI方式创建并写EXCEL文件
/// </summary>
/// <param name="xlFile">EXCEL文件</param>
/// <param name="sheetName">EXCEL表名称</param>
/// <param name="str">输出字符串数组</param>
/// <param name="row0">输出起始行</param>
/// <param name="col0">输出起始列</param>
/// <param name="nRow">行数</param>
/// <param name="nCol">列数</param>
/// <returns>true=输出EXCEL文件成功, false=输出EXCEL文件失败</returns>
public static bool WriteNewExcel(string xlFile, string sheetName, string[,] str, int row0, int col0, int nRow, int nCol)
{
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.CreateSheet(sheetName);

    for (int i = 0; i < nRow - 1; i++)
    {
        HSSFRow row = sheet.CreateRow(row0 + i);
        for (int j = 0; j < nCol - 1; j++)
        {
            row.CreateCell(col0 + j).SetCellValue(str[i, j]);
        }

    }

    using (FileStream fs = new FileStream(xlFile, FileMode.OpenOrCreate, FileAccess.ReadWrite))
    {
        workbook.Write(fs);
    }

    return true;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值