NPOI 简介(来自百度)
NPOI是指构建在POI 3.x版本之上的一个程序,NPOI可以在没有安装Office的情况下对Word或Excel文档进行读写操作。
NPOI是一个开源的C#读写Excel、WORD等微软OLE2组件文档的项目。
需要通过 NuGet 安装 NPOI 插件。
主要代码实现:
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
namespace StudentVocabularyInfo
{
/// <summary>
/// DataSet转Excel帮助类。
/// </summary>
internal class DataSetToExcel
{
/// <summary>
/// DataSet转Excel方法。
/// </summary>
/// <param name="ds">数据集。</param>
/// <param name="path">文件保存地址。</param>
/// <param name="addColumn">是否将列作为第一列数据。</param>
/// <returns></returns>
/// <exception cref="System.Exception"></exception>
public static bool DataSetToExcelXSSF(DataSet ds, string path, bool addColumn = true)
{
try
{
XSSFWorkbook hw = new XSSFWorkbook();
for (int t = 0; t < ds.Tables.Count; t++)
{
ISheet sheet2 = (ISheet)hw.CreateSheet(ds.Tables[t].TableName);
// 将列名插入到第一行数据。
if(addColumn)
{
IRow rowCol2 = (IRow)sheet2.CreateRow(0);
for (int j = 0; j < ds.Tables[t].Columns.Count; j++)
{
ICell cell = (ICell)rowCol2.CreateCell(j);
cell.SetCellValue(ds.Tables[t].Columns[j].ColumnName);
}
}
for (int i = 0; i < ds.Tables[t].Rows.Count; i++)
{
IRow row = null;
if (addColumn)
{
row = (IRow)sheet2.CreateRow(i + 1);
}
else
{
row = (IRow)sheet2.CreateRow(i);
}
for (int j = 0; j < ds.Tables[t].Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
// 获取列类型。
var columnType = ds.Tables[t].Columns[j].DataType;
// 如果列是整型数据,需要进行转换,这里需要列已经设置过属性,如果没有需要通过列数进行判断,比如第一列:j==0。
if (columnType == typeof(int))
{
int num = -1;
bool flag = int.TryParse(ds.Tables[t].Rows[i][j].ToString(), out num);
if (flag)
{
cell.SetCellValue(num);
}
else
{
cell.SetCellValue(ds.Tables[t].Rows[i][j].ToString());
}
}
else
{
if (ds.Tables[t].Rows[i][j].ToString().Contains("<br>"))
{
ICellStyle cs = hw.CreateCellStyle();
cs.WrapText = true;
cell.CellStyle = cs;
}
cell.SetCellValue(ds.Tables[t].Rows[i][j].ToString().Replace("<br>", "\r\n"));
}
}
}
}
FileStream file = new FileStream(path, FileMode.Create);
hw.Write(file);
file.Close();
if (!File.Exists(path))
{
return false;
}
return true;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
}
}
调用:
DataSetToExcel.DataSetToExcelXSSF(ds, filePath);