生活随笔
收集整理的這篇文章主要介紹了
一文搞定C#关于NPOI类库的使用读写Excel以及io流文件的写出
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一文搞定C#關(guān)于NPOI類庫的使用讀寫Excel以及io流文件的寫出
今天我們使用NPOI類庫讀寫xlsx文件,
最終實現(xiàn)的效果如圖所示
從太平洋官網(wǎng)下載相應(yīng)的類庫,大概4~5MB,不要從github下載,下載慢,且高達120MB,國內(nèi)有個碼云同樣可以下載,速度可能快一點,可以使用git命令克隆下來,速度應(yīng)該也慢,
下載加入自己的項目工程里面,添加引用即可,引用那幾個文件即可
注意添加的是dll類庫文件,其他不要,添加引用即可,瀏覽到那幾個文件,這樣使用命名空間才不會報錯,
Form1 添加幾個控件 ,button ,label TextBox 等 listBox等
雙擊控件,直接寫代碼
業(yè)務(wù)邏輯比較小,但是涉及的知識點也不少,源碼如下
using System
;
using System
.Collections
.Generic
;
using System
.ComponentModel
;
using System
.Data
;
using System
.Drawing
;
using System
.IO
;
using System
.Linq
;
using System
.Text
;
using System
.Threading
.Tasks
;
using System
.Windows
.Forms
;
using NPOI
;
using NPOI
.SS
.UserModel
;namespace DemoExcel
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void Form1_Load(object sender
, EventArgs e
){}private void PiliangBuSN(List
<string> snList
){foreach(string str
in snList
){string filepath
= "C:\\IRT\\";if (!Directory
.Exists(filepath
)){Directory
.CreateDirectory(filepath
);}string filename
= filepath
+ "\\" + str
+ "_#system-764#1_012524.xml";FileStream fs
= File
.Create(filename
);fs
.Close();StreamWriter sw
= new StreamWriter(filename
);string strNumber
= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +"
<ns1
:Boas
=\
"</ns1:XMLExport>\r\n" + "";sw
.Write(strNumber
);sw
.Flush();sw
.Close();}}List
<string> listSn
= new List<string>();private void button1_Click(object sender
, EventArgs e
){string importExcelPath
= this.textBox1
.Text
.ToString();if (this.textBox1
.Text
.Trim().Length
==0){MessageBox
.Show("請選擇一個文件");return;}string exportExcelPath
= "E:\\export.xlsx";IWorkbook workbook
= WorkbookFactory
.Create(importExcelPath
);ISheet sheet
= workbook
.GetSheetAt(0);IRow firstRow
= (IRow
)sheet
.GetRow(0);int cellCount
= firstRow
.LastCellNum
;int rowCount
= sheet
.LastRowNum
; listSn
.Clear();for (int i
= 1; i
<= rowCount
; ++i
){IRow row
= sheet
.GetRow(i
);if (row
== null) continue;string demo
= row
.GetCell(0).ToString();listSn
.Add(demo
);this.listBox1
.Items
.Add(demo
);}PiliangBuSN(listSn
);}private void button1_Click_1(object sender
, EventArgs e
){openFileDialog1
.InitialDirectory
= "C:\\";openFileDialog1
.Filter
= "xlsx文件|*.xlsx|xls文件|*.xls|文本文件|*.*|C#文件|*.cs|所有文件|*.*";openFileDialog1
.RestoreDirectory
= true;openFileDialog1
.FilterIndex
= 1;if (this.openFileDialog1
.ShowDialog()==DialogResult
.OK
){this.textBox1
.Text
= this.openFileDialog1
.FileName
.ToString();} }private void button3_Click(object sender
, EventArgs e
){this.listBox1
.Items
.Clear();}}
}
跟QT的思路差不多,包括代碼,但是這種寫法應(yīng)該更簡單更優(yōu)雅的,不得不承認C#是一種安全,優(yōu)雅,高效的編程語言.
總結(jié)
以上是生活随笔為你收集整理的一文搞定C#关于NPOI类库的使用读写Excel以及io流文件的写出的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。