C#通過NOPI讀寫Excel,並插入圖片,VS2019

C#讀寫Excel,VS2019

一、利用NOPI讀寫Excel,通過Nuget安裝NOPI
1.打開Nuget,工具->NuGet包管理工具->管理解決方案的NuGet程序包
在這裏插入圖片描述
2.搜索NOPI,並安裝
在這裏插入圖片描述
3.安裝完成
在這裏插入圖片描述
二、新建工程
1.添加panel、dataGridView、按鈕等控件,併爲datagridview添加任意列,頁面簡單佈局如下:
在這裏插入圖片描述
2.導出按鈕代碼:

			String filePath = "";
			//設置保存文件路徑
            SaveFileDialog dailog = new SaveFileDialog();
            //設置文件類型 
            dailog.Filter = ".*|*.*|數據文件(*.mdf)|*.mdf|日誌文件(*.ldf)|*.ldf";
            //設置默認文件類型顯示順序 
            dailog.FilterIndex = 1;
            //保存對話框是否記憶上次打開的目錄 
            dailog.RestoreDirectory = true;
            //點了保存按鈕進入 
            if (dailog.ShowDialog() == DialogResult.OK)
            {
                filePath = dailog.FileName.ToString(); //獲得文件路徑 
            }
            else
            {
                return;
            }

            //把datagridview轉成datatable
            DataTable dt = new DataTable();
            dt.Clear();
            foreach (DataGridViewColumn headerCell in dataGridView1.Columns)
            {
                dt.Columns.Add(headerCell.HeaderText);
            }
            foreach (DataGridViewRow item in dataGridView1.Rows)
            {
                DataRow dr = dt.NewRow();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (item.Cells[i].Value != null)
                    {
                        dr[i] = item.Cells[i].Value.ToString();
                    }
                }            
                dt.Rows.Add(dr);
            }
            Npoi_Excel.Export(dt, filePath);
            System.Diagnostics.Process.Start("explorer.exe", filePath);

3.導入按鈕代碼:

			String filePath = "";
            OpenFileDialog dialog = new OpenFileDialog();
            //表示可以多選
            dialog.Multiselect = true;
            dialog.Filter = ".*|*.*";//過濾選項設置,文本文件,所有文件。
            dialog.FilterIndex = 1;//當前使用第二個過濾字符串
            dialog.RestoreDirectory = true;//對話框關閉時恢復原目錄
            dialog.Title = "請選擇文件";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                for (int i = 1; i <= dialog.FileName.Length; i++)
                {
                    if (dialog.FileName.Substring(dialog.FileName.Length - i, 1).Equals(@"\"))
                    {
                        //更改默認路徑爲最近打開路徑
                        filePath = dialog.FileName;
                    }
                }
            }
            else
            {
                return;
            }

            DataTable dt = new DataTable();
            dt = Npoi_Excel.Import(filePath,0);
            if (dt != null)
            {
                MessageBox.Show("122");
                //dataGridView1.DataSource = table;//通常只寫這一句就可以了,但根據你的要求,用下面的循環也可以實現相同功能。
                dataGridView1.Columns.Clear();//清空列
                foreach (DataColumn column in dt.Columns)
                {
                    //爲datagridview添加列,第一個參數是列名,第二個參數是列標題
                    dataGridView1.Columns.Add(column.ColumnName, column.ColumnName);
                }
                dataGridView1.Rows.Clear();//清空行
                foreach (DataRow line in dt.Rows)
                {
                    //因爲列已經一致了,所以直接將datatable的行轉成數組就可以添加到datagridview中了
                    dataGridView1.Rows.Add(line.ItemArray);
                }
            }

4.新建一個導入、導出Excel類Npoi_Excel

using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Learning_Test
{
    class Npoi_Excel
    {

        /// <summary>
        /// 導出表格數據到 xls
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="filePath"></param>
        public static void Export(DataTable dt, string filePath)
        {
            if (!string.IsNullOrEmpty(filePath) && null != dt && dt.Rows.Count > 0)
            {
                HSSFWorkbook book = new HSSFWorkbook();
                ISheet sheet = book.CreateSheet("Test");

                sheet.DefaultColumnWidth = 30;
                sheet.DefaultRowHeight = 1400;

                IRow row = sheet.CreateRow(0);

                
                //設置單元格樣式
                ICellStyle style = book.CreateCellStyle();//創建單元格樣式對象
                IFont font = book.CreateFont(); //創建字體樣式對象
                //font.FontName = "方正舒體"; //和excel裏面的字體對應
                //font.IsItalic = true; //斜體
                font.FontHeightInPoints = 16;//字體大小
                //font.Boldweight = short.MaxValue;//字體加粗
                style.SetFont(font); //將字體樣式賦給樣式對象
                style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                style.VerticalAlignment = VerticalAlignment.Center;


                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    ICell cell = row.CreateCell(i);
                    cell.SetCellValue(dt.Columns[i].ColumnName);
                    cell.CellStyle = style;
                }
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    row = sheet.CreateRow(i + 1);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (Convert.ToString(dt.Rows[i][j]).StartsWith("http"))
                        {
                            String url = Convert.ToString(dt.Rows[i][j]);
                            byte[] bytes = Bitmap_To_Byte.Url_To_Byte(url);
                            row.CreateCell(j);

                                                       
                            //第二步:將圖片添加到workbook中  指定圖片格式 返回圖片所在workbook->Picture數組中的索引地址(從1開始)
                            int pictureIdx = book.AddPicture(bytes, PictureType.JPEG);
                            //第三步:在sheet中創建畫部
                            IDrawing patriarch = sheet.CreateDrawingPatriarch();
                            //第四步:設置錨點 (在起始單元格的X座標0-1023,Y的座標0-255,在終止單元格的X座標0-1023,Y的座標0-255,起始			   單元格列數,行數,終止單元格列數,行數)
                            IClientAnchor anchor = patriarch.CreateAnchor(0, 0, 1023, 255, j, i+1, j, i+1);

                            //第五步:創建圖片
                            IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);

                            //添加鏈接
                            //設置單元格的值
                            ICell icell = row.CreateCell(j + 1);
                            icell.SetCellValue("圖片");
                            icell.CellStyle = style;
                            //創建URL鏈接
                            HSSFHyperlink hssfHyperlink = new HSSFHyperlink(HyperlinkType.Url){Address = (Convert.ToString(dt.Rows[i][j])) };
                            icell.Hyperlink = hssfHyperlink;


                        }
                        else
                        {
                            ICell cell = row.CreateCell(j);
                            cell.SetCellValue(Convert.ToString(dt.Rows[i][j]));
                            cell.CellStyle = style;
                        }                       
                    }
                }
                using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    fs.Seek(0, SeekOrigin.Begin);
                    book.Write(fs);
                }
                book = null;
            }
        }
        
        /// <summary>
        /// 從 Xls文件導入數據到 DataTable
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="SheetName"></param>
        /// <returns></returns>
        public static DataTable Import(string filePath, String SheetName)
        {
            HSSFWorkbook hssfworkbook;
            using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                hssfworkbook = new HSSFWorkbook(file);
            }
            ISheet sheet = hssfworkbook.GetSheet(SheetName);
            if (sheet == null)
            {
                return new DataTable();
            }

            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
            DataTable dt = new DataTable(SheetName);

            for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++)
            {
                ICell cell = sheet.GetRow(0).Cells[j];
                dt.Columns.Add(cell.ToString());
            }
            rows.MoveNext();
            while (rows.MoveNext())
            {
                HSSFRow row = (HSSFRow)rows.Current;
                DataRow Row = dt.NewRow();
                for (int i = 0; i < row.LastCellNum; i++)
                {
                    ICell cell = row.GetCell(i);
                    Row[i] = cell == null ? null : cell.ToString();
                }
                dt.Rows.Add(Row);
            }
            hssfworkbook.Close();
            hssfworkbook = null;
            return dt;
        }

        /// <summary>
        /// 從 Xls文件導入數據到 DataTable
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="SheetName"></param>
        /// <returns></returns>
        public static DataTable Import(string filePath, Int32 SheetIndex)
        {
            HSSFWorkbook hssfworkbook;
            using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                hssfworkbook = new HSSFWorkbook(file);
            }
            ISheet sheet = hssfworkbook.GetSheetAt(SheetIndex);
            String SheetName = hssfworkbook.GetSheetName(SheetIndex);
            if (sheet == null)
            {
                return new DataTable();
            }

            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
            DataTable dt = new DataTable(SheetName);

            for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++)
            {
                ICell cell = sheet.GetRow(0).Cells[j];
                dt.Columns.Add(cell.ToString());
            }
            rows.MoveNext();
            while (rows.MoveNext())
            {
                HSSFRow row = (HSSFRow)rows.Current;
                DataRow Row = dt.NewRow();
                for (int i = 0; i < row.LastCellNum; i++)
                {
                    ICell cell = row.GetCell(i);
                    Row[i] = cell == null ? null : cell.ToString();
                }
                dt.Rows.Add(Row);
            }
            hssfworkbook.Close();
            hssfworkbook = null;
            return dt;
        }

    }
}

4.新建一個將網絡圖片轉爲byte數據的類Bitmap_To_Byte

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace Learning_Test
{
    class Bitmap_To_Byte
    {
        public static byte[] Url_To_Byte(String filePath)
        {
            //第一步:讀取圖片到byte數組
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filePath);

            byte[] bytes;
            using (Stream stream = request.GetResponse().GetResponseStream())
            {
                using (MemoryStream mstream = new MemoryStream())
                {
                    int count = 0;
                    byte[] buffer = new byte[1024];
                    int readNum = 0;
                    while ((readNum = stream.Read(buffer, 0,1024)) > 0)
                    {
                        count = count + readNum;
                        mstream.Write(buffer, 0, readNum);
                    }
                    mstream.Position = 0;
                    using (BinaryReader br = new BinaryReader(mstream))
                    {
                        bytes = br.ReadBytes(count);
                    }
                }
            }
            return bytes;


        }




        public static byte[] BitmapByte(Bitmap bitmap)
        {
            //Bitmap bitmap = new Bitmap();
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Jpeg);
                byte[] data = new byte[stream.Length];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, Convert.ToInt32(stream.Length));
                return data;
            }
        }


        

    }
}

三、程序完成,啓動後測試如下:
1.操作說明
在這裏插入圖片描述
2.導出後效果如圖
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章