NpoiHelper

NpoiHelper

using DBUtility;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
namespace NpoiHelper
{
	internal class NpoiHelper
	{
		public static DataTable ExcelToTable(string file)
		{
			DataTable dataTable = new DataTable();
			string a = Path.GetExtension(file).ToLower();
			DataTable result;
			using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
			{
				bool flag = a == ".xlsx";
				IWorkbook workbook;
				if (flag)
				{
					workbook = new XSSFWorkbook(fileStream);
				}
				else
				{
					bool flag2 = a == ".xls";
					if (flag2)
					{
						workbook = new HSSFWorkbook(fileStream);
					}
					else
					{
						workbook = null;
					}
				}
				bool flag3 = workbook == null;
				if (flag3)
				{
					result = null;
					return result;
				}
				ISheet sheetAt = workbook.GetSheetAt(0);
				IRow row = sheetAt.GetRow(sheetAt.FirstRowNum);
				List<int> list = new List<int>();
				for (int i = 0; i < (int)row.LastCellNum; i++)
				{
					object valueType = NpoiHelper.GetValueType(row.GetCell(i));
					bool flag4 = valueType == null || valueType.ToString() == string.Empty;
					if (flag4)
					{
						dataTable.Columns.Add(new DataColumn("Columns" + i.ToString()));
					}
					else
					{
						dataTable.Columns.Add(new DataColumn(valueType.ToString()));
					}
					list.Add(i);
				}
				for (int j = sheetAt.FirstRowNum + 1; j <= sheetAt.LastRowNum; j++)
				{
					DataRow dataRow = dataTable.NewRow();
					bool flag5 = false;
					foreach (int current in list)
					{
						dataRow[current] = NpoiHelper.GetValueType(sheetAt.GetRow(j).GetCell(current));
						bool flag6 = dataRow[current] != null && dataRow[current].ToString() != string.Empty;
						if (flag6)
						{
							flag5 = true;
						}
					}
					bool flag7 = flag5;
					if (flag7)
					{
						dataTable.Rows.Add(dataRow);
					}
				}
			}
			result = dataTable;
			return result;
		}
		public static void TableToExcel(DataTable dt, string file)
		{
			string a = Path.GetExtension(file).ToLower();
			bool flag = a == ".xlsx";
			IWorkbook workbook;
			if (flag)
			{
				workbook = new XSSFWorkbook();
			}
			else
			{
				bool flag2 = a == ".xls";
				if (flag2)
				{
					workbook = new HSSFWorkbook();
				}
				else
				{
					workbook = null;
				}
			}
			bool flag3 = workbook == null;
			if (!flag3)
			{
				ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);
				IRow row = sheet.CreateRow(0);
				for (int i = 0; i < dt.Columns.Count; i++)
				{
					ICell cell = row.CreateCell(i);
					cell.SetCellValue(dt.Columns[i].ColumnName);
				}
				for (int j = 0; j < dt.Rows.Count; j++)
				{
					IRow row2 = sheet.CreateRow(j + 1);
					for (int k = 0; k < dt.Columns.Count; k++)
					{
						ICell cell2 = row2.CreateCell(k);
						bool flag4 = PageValidate.IsNumber(dt.Rows[j][k].ToString());
						if (flag4)
						{
							cell2.SetCellValue((double)Convert.ToInt32(dt.Rows[j][k].ToString()));
						}
						else
						{
							bool flag5 = PageValidate.IsDecimal(dt.Rows[j][k].ToString());
							if (flag5)
							{
								cell2.SetCellValue(Convert.ToDouble(dt.Rows[j][k].ToString()));
							}
							else
							{
								cell2.SetCellValue(dt.Rows[j][k].ToString());
							}
						}
					}
				}
				MemoryStream memoryStream = new MemoryStream();
				workbook.Write(memoryStream);
				byte[] array = memoryStream.ToArray();
				using (FileStream fileStream = new FileStream(file, FileMode.Create, FileAccess.Write))
				{
					fileStream.Write(array, 0, array.Length);
					fileStream.Flush();
				}
			}
		}
		private static object GetValueType(ICell cell)
		{
			bool flag = cell == null;
			object result;
			if (flag)
			{
				result = null;
			}
			else
			{
				switch (cell.CellType)
				{
				case CellType.Numeric:
					result = cell.NumericCellValue;
					return result;
				case CellType.String:
					result = cell.StringCellValue;
					return result;
				case CellType.Blank:
					result = null;
					return result;
				case CellType.Boolean:
					result = cell.BooleanCellValue;
					return result;
				case CellType.Error:
					result = cell.ErrorCellValue;
					return result;
				}
				result = "=" + cell.CellFormula;
			}
			return result;
		}
	}
}

以下是一个示例 C# Npoi 导出 Word 和 Excel 的 Helper 类: ```csharp using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.XWPF.UserModel; using System.Collections.Generic; using System.IO; namespace MyProject.Helpers { public class NpoiHelper { /// <summary> /// 导出 Excel /// </summary> /// <param name="data">数据</param> /// <param name="filePath">文件路径</param> public static bool ExportExcel(List<List<string>> data, string filePath) { IWorkbook workbook; if (Path.GetExtension(filePath) == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = new XSSFWorkbook(); } ISheet sheet = workbook.CreateSheet("Sheet1"); for (int i = 0; i < data.Count; i++) { IRow row = sheet.CreateRow(i); for (int j = 0; j < data[i].Count; j++) { ICell cell = row.CreateCell(j); cell.SetCellValue(data[i][j]); } } using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { workbook.Write(stream); } return true; } /// <summary> /// 导出 Word /// </summary> /// <param name="data">数据</param> /// <param name="filePath">文件路径</param> public static bool ExportWord(List<string> data, string filePath) { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); foreach (string s in data) { XWPFRun r = p.CreateRun(); r.SetText(s); r.AddCarriageReturn(); } using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { doc.Write(stream); } return true; } } } ``` 使用示例: ```csharp // 导出 Excel List<List<string>> data = new List<List<string>>() { new List<string> { "姓名", "年龄", "性别" }, new List<string> { "张三", "18", "男" }, new List<string> { "李四", "20", "女" } }; NpoiHelper.ExportExcel(data, "D:\\test.xlsx"); // 导出 Word List<string> data = new List<string>() { "这是一段文本。", "这是另一段文本。" }; NpoiHelper.ExportWord(data, "D:\\test.docx"); ``` 注意,使用该 Helper 类需要安装 NPOI NuGet 包。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值