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
  • Timer是什麼 Timer 是一種用於創建定期粒度行為的機制。 與標準的 .NET System.Threading.Timer 類相似,Orleans 的 Timer 允許在一段時間後執行特定的操作,或者在特定的時間間隔內重覆執行操作。 它在分散式系統中具有重要作用,特別是在處理需要周期性執行的 ...
  • 前言 相信很多做WPF開發的小伙伴都遇到過表格類的需求,雖然現有的Grid控制項也能實現,但是使用起來的體驗感並不好,比如要實現一個Excel中的表格效果,估計你能想到的第一個方法就是套Border控制項,用這種方法你需要控制每個Border的邊框,並且在一堆Bordr中找到Grid.Row,Grid. ...
  • .NET C#程式啟動閃退,目錄導致的問題 這是第2次踩這個坑了,很小的編程細節,容易忽略,所以寫個博客,分享給大家。 1.第一次坑:是windows 系統把程式運行成服務,找不到配置文件,原因是以服務運行它的工作目錄是在C:\Windows\System32 2.本次坑:WPF桌面程式通過註冊表設 ...
  • 在分散式系統中,數據的持久化是至關重要的一環。 Orleans 7 引入了強大的持久化功能,使得在分散式環境下管理數據變得更加輕鬆和可靠。 本文將介紹什麼是 Orleans 7 的持久化,如何設置它以及相應的代碼示例。 什麼是 Orleans 7 的持久化? Orleans 7 的持久化是指將 Or ...
  • 前言 .NET Feature Management 是一個用於管理應用程式功能的庫,它可以幫助開發人員在應用程式中輕鬆地添加、移除和管理功能。使用 Feature Management,開發人員可以根據不同用戶、環境或其他條件來動態地控制應用程式中的功能。這使得開發人員可以更靈活地管理應用程式的功 ...
  • 在 WPF 應用程式中,拖放操作是實現用戶交互的重要組成部分。通過拖放操作,用戶可以輕鬆地將數據從一個位置移動到另一個位置,或者將控制項從一個容器移動到另一個容器。然而,WPF 中預設的拖放操作可能並不是那麼好用。為瞭解決這個問題,我們可以自定義一個 Panel 來實現更簡單的拖拽操作。 自定義 Pa ...
  • 在實際使用中,由於涉及到不同編程語言之間互相調用,導致C++ 中的OpenCV與C#中的OpenCvSharp 圖像數據在不同編程語言之間難以有效傳遞。在本文中我們將結合OpenCvSharp源碼實現原理,探究兩種數據之間的通信方式。 ...
  • 一、前言 這是一篇搭建許可權管理系統的系列文章。 隨著網路的發展,信息安全對應任何企業來說都越發的重要,而本系列文章將和大家一起一步一步搭建一個全新的許可權管理系統。 說明:由於搭建一個全新的項目過於繁瑣,所有作者將挑選核心代碼和核心思路進行分享。 二、技術選擇 三、開始設計 1、自主搭建vue前端和. ...
  • Csharper中的表達式樹 這節課來瞭解一下表示式樹是什麼? 在C#中,表達式樹是一種數據結構,它可以表示一些代碼塊,如Lambda表達式或查詢表達式。表達式樹使你能夠查看和操作數據,就像你可以查看和操作代碼一樣。它們通常用於創建動態查詢和解析表達式。 一、認識表達式樹 為什麼要這樣說?它和委托有 ...
  • 在使用Django等框架來操作MySQL時,實際上底層還是通過Python來操作的,首先需要安裝一個驅動程式,在Python3中,驅動程式有多種選擇,比如有pymysql以及mysqlclient等。使用pip命令安裝mysqlclient失敗應如何解決? 安裝的python版本說明 機器同時安裝了 ...