一、讀取excel表內(nèi)容
(1)首先在程序:“引用”右鍵--點(diǎn)擊“管理NuGet程序包” (我這里是已經(jīng)引入過(guò)了,所以會(huì)顯示引用中有NPOI)
?
(2)在“瀏覽”處搜索“NPOI”,選擇適當(dāng)版本安裝(需要聯(lián)網(wǎng))
?
(3)在程序中引入相應(yīng)的命名空間,編寫(xiě)讀取excel表格的封裝代碼(萬(wàn)能)
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
#region 讀取Excel數(shù)據(jù)
/// <summary>
/// 將excel中的數(shù)據(jù)導(dǎo)入到DataTable中
/// </summary>
/// <param name="fileName">文件路徑</param>
/// <param name="sheetName">excel工作薄sheet的名稱(chēng)</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名,true是</param>
/// <returns>返回的DataTable</returns>
public static DataTable ExcelToDatatable(string fileName, string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
FileStream fs;
IWorkbook workbook = null;
int cellCount = 0;//列數(shù)
int rowCount = 0;//行數(shù)
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
{
workbook = new XSSFWorkbook(fs);
}
else if (fileName.IndexOf(".xls") > 0) // 2003版本
{
workbook = new HSSFWorkbook(fs);
}
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);//根據(jù)給定的sheet名稱(chēng)獲取數(shù)據(jù)
}
else
{
//也可以根據(jù)sheet編號(hào)來(lái)獲取數(shù)據(jù)
sheet = workbook.GetSheetAt(0);//獲取第幾個(gè)sheet表(此處表示如果沒(méi)有給定sheet名稱(chēng),默認(rèn)是第一個(gè)sheet表)
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
cellCount = firstRow.LastCellNum; //第一行最后一個(gè)cell的編號(hào) 即總的列數(shù)
if (isFirstRowColumn)//如果第一行是標(biāo)題行
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)//第一行列數(shù)循環(huán)
{
DataColumn column = new DataColumn(firstRow.GetCell(i).StringCellValue);//獲取標(biāo)題
data.Columns.Add(column);//添加列
}
startRow = sheet.FirstRowNum + 1;//1(即第二行,第一行0從開(kāi)始)
}
else
{
startRow = sheet.FirstRowNum;//0
}
//最后一行的標(biāo)號(hào)
rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)//循環(huán)遍歷所有行
{
IRow row = sheet.GetRow(i);//第幾行
if (row == null)
{
continue; //沒(méi)有數(shù)據(jù)的行默認(rèn)是null;
}
//將excel表每一行的數(shù)據(jù)添加到datatable的行中
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,沒(méi)有數(shù)據(jù)的單元格都默認(rèn)是null
{
dataRow[j] = row.GetCell(j).ToString();
}
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return null;
}
}
#endregion
(4)調(diào)用上述讀取excel表的方法,讀取數(shù)據(jù)并存取
DataTable dt = ExcelToDatatable(@"C:\Users\Administrator\Desktop\35t敞頂箱(2)\4-11月連續(xù)日期每天需求量.xlsx", "Sheet1", true);
//將excel表格數(shù)據(jù)存入list集合中
//EachdayTX定義的類(lèi),字段值對(duì)應(yīng)excel表中的每一列
List<EachdayTX> eachdayTX = new List<EachdayTX>();
foreach (DataRow dr in dt.Rows)
{
EachdayTX model = new EachdayTX
{
Sta=dr[0].ToString()+"站",//excel表中第一列的值,依次類(lèi)推
Date=dr[1].ToString(),
TXnum=Convert.ToInt32(dr[2])
};
eachdayTX.Add(model);
}
public class EachdayTX
{
public string Sta { get; set; }
public string Date { get; set; }
public int TXnum { get; set; }
}
二、數(shù)據(jù)寫(xiě)入excel表
(1)同樣按照上面讀取excel中的第一步,添加NPOI引用。
(2)添加命名空間,編寫(xiě)將數(shù)據(jù)寫(xiě)入excel表的代碼文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-671039.html
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
//此處是將list集合寫(xiě)入excel表,Supply也是自己定義的類(lèi),每一個(gè)字段對(duì)應(yīng)需要寫(xiě)入excel表的每一列的數(shù)據(jù)
//一次最多能寫(xiě)65535行數(shù)據(jù),超過(guò)需將list集合拆分,分多次寫(xiě)入
#region 寫(xiě)入excel
public static bool ListToExcel(List<Supply> list)
{
bool result = false;
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1");//創(chuàng)建一個(gè)名稱(chēng)為Sheet0的表;
IRow row = sheet.CreateRow(0);//(第一行寫(xiě)標(biāo)題)
row.CreateCell(0).SetCellValue("標(biāo)題1");//第一列標(biāo)題,以此類(lèi)推
row.CreateCell(1).SetCellValue("標(biāo)題2");
row.CreateCell(2).SetCellValue("標(biāo)題3");
int count = list.Count;//
int max = 65535;//最大行數(shù)限制
if (count < max)
{
//每一行依次寫(xiě)入
for (int i = 0; i < list.Count; i++)
{
row = sheet.CreateRow(i + 1);//i+1:從第二行開(kāi)始寫(xiě)入(第一行可同理寫(xiě)標(biāo)題),i從第一行寫(xiě)入
row.CreateCell(0).SetCellValue(list[i].Value1);//第一列的值
row.CreateCell(1).SetCellValue(list[i].Value2);//第二列的值
row.CreateCell(2).SetCellValue(list[i].Value3);
}
//文件寫(xiě)入的位置
using (FileStream fs = File.OpenWrite(@"C:\Users\20882\Desktop\結(jié)果.xls"))
{
workbook.Write(fs);//向打開(kāi)的這個(gè)xls文件中寫(xiě)入數(shù)據(jù)
result = true;
}
}
else
{
Console.WriteLine("超過(guò)行數(shù)限制!");
result = false;
}
return result;
}
#endregion
(3)調(diào)用上述寫(xiě)入excel表的代碼,寫(xiě)入數(shù)據(jù)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-671039.html
List<Supply> data = new List<Supply>();
//假設(shè)data 已經(jīng)存入了數(shù)據(jù),根據(jù)自己需要添加數(shù)據(jù)
data.Add(new Supply
{
Value1 = "1",
Value2= "haha",
Value3="111",
});
bool a = ListToExcel(data);//調(diào)用寫(xiě)入excel的方法,寫(xiě)入數(shù)據(jù)
public class Supply
{
public string Value1{ get; set; }
public string Value2{ get; set; }
public string Value3{ get; set; }
}
到了這里,關(guān)于C# .NET讀取和寫(xiě)入Excel表數(shù)據(jù)(手把手教)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!