我尝试使用NPOI在另一个工作簿xlsx中复制工作表,但它失败了。 有一个xls文件here
的例子我没有找到等效的XSSF函数。 我总是得到一个损坏的文件。
所有例子都使用HSSF,你能帮助我吗?
这是我的代码不起作用
List<string> fileToMerge = new List<string>();
fileToMerge.Add("file1.xlsx");
fileToMerge.Add("file2.xlsx");
MergeFiles(fileToMerge, "fileMerged.xlsx");
private void MergeFiles(List<string> filenames, string outFilename)
{
XSSFWorkbook merged = new XSSFWorkbook();
foreach (string filename in filenames)
{
XSSFWorkbook workbook = GetWorkbook(filename);
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
XSSFSheet sheet1 = workbook.GetSheetAt(i) as XSSFSheet;
merged.Add(sheet1.CopySheet(sheet1.SheetName, true));
}
}
SaveWorkbook(merged, outFilename);
}
private XSSFWorkbook GetWorkbook(string filename)
{
XSSFWorkbook workbook = new XSSFWorkbook();
string path = Path.Combine(Environment.CurrentDirectory, filename);
if (!File.Exists(path))
{
Console.WriteLine("This file does not exist: " + path);
Environment.Exit(7);
}
else
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
workbook = new XSSFWorkbook(fs);
fs.Close();
fs.Dispose();
}
return workbook;
}
private void SaveWorkbook(XSSFWorkbook workbook, string fileName)
{
// metadata
workbook.GetProperties().CoreProperties.Creator = "My Company " + DateTime.Now.Year.ToString();
workbook.GetProperties().ExtendedProperties.props.AddNewProperties().Company = "My Company";
FileStream sw = File.Create(fileName);
workbook.Write(sw);
sw.Close();
sw.Dispose();
}
提前谢谢。
答案 0 :(得分:0)
public FileResult DownloadFile()
{
// code to create workbook
using (var exportData = new MemoryStream())
{
workbook.Write(exportData);
string saveAsFileName = string.Format("MembershipExport-{0:d}.xls", DateTime.Now).Replace("/", "-");
byte[] bytes = exportData.ToArray();
return File(bytes, "application/vnd.ms-excel", saveAsFileName);
}
}