1.使用EPPLUS
using System.IO;
using OfficeOpenXml;
void SplitExcel(string filePath)
{
using (var package = new ExcelPackage(new FileInfo(filePath)))
{
foreach (var worksheet in package.Workbook.Worksheets)
{
string newFilePath = worksheet.Name + ".xlsx";//将工作表的名称作为新文件的文件名
using (var pkg = new ExcelPackage(new FileInfo(newFilePath)))
{
pkg.Workbook.Worksheets.Add("Sheet1", worksheet);//copy
pkg.Save();
}
}
}
}
2.使用NPOI
using System.IO;
using NPOI.HSSF.UserModel;
void SplitExcel(string filePath)
{
using (var srcFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
var srcWorkbook = new HSSFWorkbook(srcFileStream); //xls格式用HSSF,如果是xlsx用XSSF
for (int sheetIndex = 0; sheetIndex < srcWorkbook.NumberOfSheets; sheetIndex++)
{
var sheetName = srcWorkbook.GetSheetName(sheetIndex); //获取sheet名用来作为新文件的文件名,
//按需要进行修改
var srcWorksheet = srcWorkbook.GetSheetAt(sheetIndex) as HSSFSheet;
string newFilePath = sheetName + ".xls";
using (var dstFileStream = new FileStream(newFilePath,
FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
var dstWorkbook = new HSSFWorkbook();
srcWorksheet.CopyTo(dstWorkbook, "Sheet1", true, true);//将源工作簿中的工作表worksheet到
//新工作簿中,命名为Sheet1
dstWorkbook.Write(dstFileStream);
}
}
}
}
评论 (0)