ASP.NET操作Excel

来源:https://www.cnblogs.com/yijieyufu/archive/2019/12/13/12033913.html
-Advertisement-
Play Games

使用NPOI操作Excel,無需Office COM組件 部分代碼來自於:https://docs.microsoft.com/zh-tw/previous-versions/ee818993(v=msdn.10)?redirectedfrom=MSDN using System.Data; usi ...


使用NPOI操作Excel,無需Office COM組件

部分代碼來自於:https://docs.microsoft.com/zh-tw/previous-versions/ee818993(v=msdn.10)?redirectedfrom=MSDN

using System.Data;
using System.IO;
using System.Text;
using System.Web;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

/// <summary>
/// 使用NPOI操作Excel,無需Office COM組件
/// 部分代碼取自http://msdn.microsoft.com/zh-tw/ee818993.asp
/// </summary>
public class ExcelRender
{
    /// <summary>
    /// 根據Excel列類型獲取列的值
    /// </summary>
    /// <param name="cell">Excel列</param>
    /// <returns></returns>
    private static string GetCellValue(ICell cell)
    {
        if (cell == null)
            return string.Empty;
        switch (cell.CellType)
        {
            case CellType.BLANK:
                return string.Empty;
            case CellType.BOOLEAN:
                return cell.BooleanCellValue.ToString();
            case CellType.ERROR:
                return cell.ErrorCellValue.ToString();
            case CellType.NUMERIC:
            case CellType.Unknown:
            default:
                return cell.ToString();//This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number
            case CellType.STRING:
                return cell.StringCellValue;
            case CellType.FORMULA:
                try
                {
                    HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                    e.EvaluateInCell(cell);
                    return cell.ToString();
                }
                catch
                {
                    return cell.NumericCellValue.ToString();
                } 
        }
    }

    /// <summary>
    /// 自動設置Excel列寬
    /// </summary>
    /// <param name="sheet">Excel表</param>
    private static void AutoSizeColumns(ISheet sheet)
    {
        if (sheet.PhysicalNumberOfRows > 0)
        {
            IRow headerRow = sheet.GetRow(0);

            for (int i = 0, l = headerRow.LastCellNum; i < l; i++)
            {
                sheet.AutoSizeColumn(i);
            }
        }
    }

    /// <summary>
    /// 保存Excel文檔流到文件
    /// </summary>
    /// <param name="ms">Excel文檔流</param>
    /// <param name="fileName">文件名</param>
    private static void SaveToFile(MemoryStream ms, string fileName)
    {
        using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
        {
            byte[] data = ms.ToArray();

            fs.Write(data, 0, data.Length);
            fs.Flush();

            data = null;
        }
    }

    /// <summary>
    /// 輸出文件到瀏覽器
    /// </summary>
    /// <param name="ms">Excel文檔流</param>
    /// <param name="context">HTTP上下文</param>
    /// <param name="fileName">文件名</param>
    private static void RenderToBrowser(MemoryStream ms, HttpContext context, string fileName)
    {
        if (context.Request.Browser.Browser == "IE")
            fileName = HttpUtility.UrlEncode(fileName);
        context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
        context.Response.BinaryWrite(ms.ToArray());
    }

    /// <summary>
    /// DataReader轉換成Excel文檔流
    /// </summary>
    /// <param name="reader"></param>
    /// <returns></returns>
    public static MemoryStream RenderToExcel(IDataReader reader)
    {
        MemoryStream ms = new MemoryStream();

        using (reader)
        {
            using (IWorkbook workbook = new HSSFWorkbook())
            {
                using (ISheet sheet = workbook.CreateSheet())
                {
                    IRow headerRow = sheet.CreateRow(0);
                    int cellCount = reader.FieldCount;

                    // handling header.
                    for (int i = 0; i < cellCount; i++)
                    {
                        headerRow.CreateCell(i).SetCellValue(reader.GetName(i));
                    }

                    // handling value.
                    int rowIndex = 1;
                    while (reader.Read())
                    {
                        IRow dataRow = sheet.CreateRow(rowIndex);

                        for (int i = 0; i < cellCount; i++)
                        {
                            dataRow.CreateCell(i).SetCellValue(reader[i].ToString());
                        }

                        rowIndex++;
                    }

                    AutoSizeColumns(sheet);

                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                }
            }
        }
        return ms;
    }

    /// <summary>
    /// DataReader轉換成Excel文檔流,並保存到文件
    /// </summary>
    /// <param name="reader"></param>
    /// <param name="fileName">保存的路徑</param>
    public static void RenderToExcel(IDataReader reader, string fileName)
    {
        using (MemoryStream ms = RenderToExcel(reader))
        {
            SaveToFile(ms, fileName);
        }
    }

    /// <summary>
    /// DataReader轉換成Excel文檔流,並輸出到客戶端
    /// </summary>
    /// <param name="reader"></param>
    /// <param name="context">HTTP上下文</param>
    /// <param name="fileName">輸出的文件名</param>
    public static void RenderToExcel(IDataReader reader, HttpContext context, string fileName)
    {
        using (MemoryStream ms = RenderToExcel(reader))
        {
            RenderToBrowser(ms, context, fileName);
        }
    }

    /// <summary>
    /// DataTable轉換成Excel文檔流
    /// </summary>
    /// <param name="table"></param>
    /// <returns></returns>
    public static MemoryStream RenderToExcel(DataTable table)
    {
        MemoryStream ms = new MemoryStream();

        using (table)
        {
            using (IWorkbook workbook = new HSSFWorkbook())
            {
                using (ISheet sheet = workbook.CreateSheet())
                {
                    IRow headerRow = sheet.CreateRow(0);

                    // handling header.
                    foreach (DataColumn column in table.Columns)
                        headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value

                    // handling value.
                    int rowIndex = 1;

                    foreach (DataRow row in table.Rows)
                    {
                        IRow dataRow = sheet.CreateRow(rowIndex);

                        foreach (DataColumn column in table.Columns)
                        {
                            dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                        }

                        rowIndex++;
                    }
                    AutoSizeColumns(sheet);

                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                }
            }
        }
        return ms;
    }

    /// <summary>
    /// DataTable轉換成Excel文檔流,並保存到文件
    /// </summary>
    /// <param name="table"></param>
    /// <param name="fileName">保存的路徑</param>
    public static void RenderToExcel(DataTable table, string fileName)
    {
        using (MemoryStream ms = RenderToExcel(table))
        {
            SaveToFile(ms, fileName);
        }
    }

    /// <summary>
    /// DataTable轉換成Excel文檔流,並輸出到客戶端
    /// </summary>
    /// <param name="table"></param>
    /// <param name="response"></param>
    /// <param name="fileName">輸出的文件名</param>
    public static void RenderToExcel(DataTable table, HttpContext context, string fileName)
    {
        using (MemoryStream ms = RenderToExcel(table))
        {
            RenderToBrowser(ms, context, fileName);
        }
    }

    /// <summary>
    /// Excel文檔流是否有數據
    /// </summary>
    /// <param name="excelFileStream">Excel文檔流</param>
    /// <returns></returns>
    public static bool HasData(Stream excelFileStream)
    {
        return HasData(excelFileStream, 0);
    }

    /// <summary>
    /// Excel文檔流是否有數據
    /// </summary>
    /// <param name="excelFileStream">Excel文檔流</param>
    /// <param name="sheetIndex">表索引號,如第一個表為0</param>
    /// <returns></returns>
    public static bool HasData(Stream excelFileStream, int sheetIndex)
    {
        using (excelFileStream)
        {
            using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
            {
                if (workbook.NumberOfSheets > 0)
                {
                    if (sheetIndex < workbook.NumberOfSheets)
                    {
                        using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
                        {
                            return sheet.PhysicalNumberOfRows > 0;
                        }
                    }
                }
            }
        }
        return false;
    }

    /// <summary>
    /// Excel文檔流轉換成DataTable
    /// 第一行必須為標題行
    /// </summary>
    /// <param name="excelFileStream">Excel文檔流</param>
    /// <param name="sheetName">表名稱</param>
    /// <returns></returns>
    public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName)
    {
        return RenderFromExcel(excelFileStream, sheetName, 0);
    }

    /// <summary>
    /// Excel文檔流轉換成DataTable
    /// </summary>
    /// <param name="excelFileStream">Excel文檔流</param>
    /// <param name="sheetName">表名稱</param>
    /// <param name="headerRowIndex">標題行索引號,如第一行為0</param>
    /// <returns></returns>
    public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex)
    {
        DataTable table = null;

        using (excelFileStream)
        {
            using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
            {
                using (ISheet sheet = workbook.GetSheet(sheetName))
                {
                    table = RenderFromExcel(sheet, headerRowIndex);
                }
            }
        }
        return table;
    }

    /// <summary>
    /// Excel文檔流轉換成DataTable
    /// 預設轉換Excel的第一個表
    /// 第一行必須為標題行
    /// </summary>
    /// <param name="excelFileStream">Excel文檔流</param>
    /// <returns></returns>
    public static DataTable RenderFromExcel(Stream excelFileStream)
    {
        return RenderFromExcel(excelFileStream, 0, 0);
    }

    /// <summary>
    /// Excel文檔流轉換成DataTable
    /// 第一行必須為標題行
    /// </summary>
    /// <param name="excelFileStream">Excel文檔流</param>
    /// <param name="sheetIndex">表索引號,如第一個表為0</param>
    /// <returns></returns>
    public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex)
    {
        return RenderFromExcel(excelFileStream, sheetIndex, 0);
    }

    /// <summary>
    /// Excel文檔流轉換成DataTable
    /// </summary>
    /// <param name="excelFileStream">Excel文檔流</param>
    /// <param name="sheetIndex">表索引號,如第一個表為0</param>
    /// <param name="headerRowIndex">標題行索引號,如第一行為0</param>
    /// <returns></returns>
    public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex, int headerRowIndex)
    {
        DataTable table = null;

        using (excelFileStream)
        {
            using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
            {
                using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
                {
                    table = RenderFromExcel(sheet, headerRowIndex);
                }
            }
        }
        return table;
    }

    /// <summary>
    /// Excel表格轉換成DataTable
    /// </summary>
    /// <param name="sheet">表格</param>
    /// <param name="headerRowIndex">標題行索引號,如第一行為0</param>
    /// <returns></returns>
    private static DataTable RenderFromExcel(ISheet sheet, int headerRowIndex)
    {
        DataTable table = new DataTable();

        IRow headerRow = sheet.GetRow(headerRowIndex);
        int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
        int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1

        //handling header.
        for (int i = headerRow.FirstCellNum; i < cellCount; i++)
        {
            DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
            table.Columns.Add(column);
        }

        for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
        {
            IRow row = sheet.GetRow(i);
            DataRow dataRow = table.NewRow();

            if (row != null)
            {
                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                        dataRow[j] = GetCellValue(row.GetCell(j));
                }
            }

            table.Rows.Add(dataRow);
        }

        return table;
    }

    /// <summary>
    /// Excel文檔導入到資料庫
    /// 預設取Excel的第一個表
    /// 第一行必須為標題行
    /// </summary>
    /// <param name="excelFileStream">Excel文檔流</param>
    /// <param name="insertSql">插入語句</param>
    /// <param name="dbAction">更新到資料庫的方法</param>
    /// <returns></returns>
    public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction)
    {
        return RenderToDb(excelFileStream, insertSql, dbAction, 0, 0);
    }

    public delegate int DBAction(string sql, params IDataParameter[] parameters);

    /// <summary>
    /// Excel文檔導入到資料庫
    /// </summary>
    /// <param name="excelFileStream">Excel文檔流</param>
    /// <param name="insertSql">插入語句</param>
    /// <param name="dbAction">更新到資料庫的方法</param>
    /// <param name="sheetIndex">表索引號,如第一個表為0</param>
    /// <param name="headerRowIndex">標題行索引號,如第一行為0</param>
    /// <returns></returns>
    public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction, int sheetIndex, int headerRowIndex)
    {
        int rowAffected = 0;
        using (excelFileStream)
        {
            using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
            {
                using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
                {
                    StringBuilder builder = new StringBuilder();

                    IRow headerRow = sheet.GetRow(headerRowIndex);
                    int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
                    int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1

                    for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row != null)
                        {
                            builder.Append(insertSql);
                            builder.Append(" values (");
                            for (int j = row.FirstCellNum; j < cellCount; j++)
                            {
                                builder.AppendFormat("'{0}',", GetCellValue(row.GetCell(j)).Replace("'", "''"));
                            }
                            builder.Length = builder.Length - 1;
                            builder.Append(");");
                        }

                        if ((i % 50 == 0 || i == rowCount) && builder.Length > 0)
                        {
                            //每50條記錄一次批量插入到資料庫
                            rowAffected += dbAction(builder.ToString());
                            builder.Length = 0;
                        }
                    }
                }
            }
        }
        return rowAffected;
    }
}

弄一個DBheple 就可以完成該操作Excel


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...