简体   繁体   English

NPOI c#在另一个工作簿xlsx中复制工作表

[英]NPOI c# copy worksheet in another workbook xlsx

I try to copy a worksheet in another workbook xlsx with NPOI but it fails. 我尝试使用NPOI将工作表复制到另一个工作簿xlsx中,但是失败。 There is an example for xls files here 有一个例子的XLS文件在这里

I don't find the equivalent XSSF functions. 我找不到等效的XSSF函数。 I always get a corrupted file. 我总是收到损坏的文件。

All examples use HSSF, can you help me? 所有示例均使用HSSF,您能帮我吗?

Here is my code does not work 这是我的代码不起作用

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();
}

Thank you in advance. 先感谢您。

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);
    }
}

Taken from post how to download a xls file generated by NPOI in ASP MVC 从帖子中获取如何在ASP MVC中下载NPOI生成的xls文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM