从C#创建xlsx(Excel)文件

14

这是一个只能创建xls文件的代码。但是我想创建xlsx(Excel)文件,我该如何在这个代码中实现,或者是否有另一种代码可以用来创建xlsx文件。

using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;


Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                MessageBox.Show("Excel is not properly installed!!");
                return;
            }


            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            xlWorkSheet.Cells[1, 1] = "ID";
            xlWorkSheet.Cells[1, 2] = "Name";
            xlWorkSheet.Cells[2, 1] = "1";
            xlWorkSheet.Cells[2, 2] = "One";
            xlWorkSheet.Cells[3, 1] = "2";
            xlWorkSheet.Cells[3, 2] = "Two";



            xlWorkBook.SaveAs("d:\\vdfgdfg.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            Marshal.ReleaseComObject(xlWorkSheet);
            Marshal.ReleaseComObject(xlWorkBook);
            Marshal.ReleaseComObject(xlApp);

            MessageBox.Show("Excel file created , you can find the file d:\\csharp-Excel.xls");
        }

你看过https://www.nuget.org/packages/GemBox.Spreadsheet吗?它是一个不需要Excel的组件,对于小表格有免费许可证。 - Esben Skov Pedersen
可能对你有帮助的是,你只需要在代码中将 xlWorkBookNormal 改为 xlOpenXMLWorkbook,当然还要将文件名从 xls 改为 xlsx :D - mw509
6个回答

23
请尝试下面更新后的代码。
    public void CreateExcel()
    {
      Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

        if (xlApp == null)
        {
            MessageBox.Show("Excel is not properly installed!!");
            return;
        }


        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        xlWorkSheet.Cells[1, 1] = "ID";
        xlWorkSheet.Cells[1, 2] = "Name";
        xlWorkSheet.Cells[2, 1] = "1";
        xlWorkSheet.Cells[2, 2] = "One";
        xlWorkSheet.Cells[3, 1] = "2";
        xlWorkSheet.Cells[3, 2] = "Two";

                  //Here saving the file in xlsx
                xlWorkBook.SaveAs("d:\\vdfgdfg.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, misValue,
                misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);


        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        Marshal.ReleaseComObject(xlWorkSheet);
        Marshal.ReleaseComObject(xlWorkBook);
        Marshal.ReleaseComObject(xlApp);

        MessageBox.Show("Excel file created , you can find the file d:\\csharp-Excel.xlsx");
    }

我曾经尝试过,但它不起作用。它只保存了一个xlsx文件,但无法打开它。 - Malinda Peiris
请尝试我的更新代码。它正常工作。它将保存为 .XLSX 的 Excel 文件并打开它。 - Pranav_Systematix

2

请看我的SwiftExcel库。它是为了快速、简便的excel输出而设计的,更重要的是 - 高性能。

using (var ew = new ExcelWriter("C:\\temp\\test.xlsx"))
{
    ew.Write("ID", 1, 1);
    ew.Write("Name", 2, 1);

    ew.Write("1", 1, 2);
    ew.Write("One", 2, 2);

    ew.Write("2", 1, 3);
    ew.Write("Two", 2, 3);
}

同时它是根据MIT许可证发布的。 - Naughton

1

1

Replace the following line:

 xlWorkBook.SaveAs("d:\\vdfgdfg.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

使用这行代码:xlWorkBook.SaveAs("d:\\vdfgdfg.xlsx");保存工作簿。

1
你可以使用NPOI库来创建Excel文档。它不需要安装Office,也不使用Interop / COM+。同时,它还支持.NET Core。
using var workbook = new XSSFWorkbook();

var sheet = workbook.CreateSheet("Sheet1");

int rowIndex = 0;

var row = sheet.CreateRow(rowIndex++);
int cellIndex = 0;
row.CreateCell(cellIndex++).SetCellValue("ID");
row.CreateCell(cellIndex++).SetCellValue("Name");

var row = sheet.CreateRow(rowIndex++);
cellIndex = 0;
row.CreateCell(cellIndex++).SetCellValue("1");
row.CreateCell(cellIndex++).SetCellValue("One");

var row = sheet.CreateRow(rowIndex++);
cellIndex = 0;
row.CreateCell(cellIndex++).SetCellValue("2");
row.CreateCell(cellIndex++).SetCellValue("Two");


string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
string xlsxPath = Path.Combine(path, $"vdfgdfg.xlsx");

using var fileStream = new FileStream(xlsxPath, FileMode.Create, FileAccess.Write);
workbook.Write(fileStream);

链接:
- NuGet: [https://www.nuget.org/packages/NPOI](https://www.nuget.org/packages/NPOI) - 相当不错的介绍(HTTP!):[http://www.independent-software.com/introduction-to-npoi.html](http://www.independent-software.com/introduction-to-npoi.html) - 入门指南:[https://github.com/nissl-lab/npoi/wiki/Getting-Started-with-NPOI](https://github.com/nissl-lab/npoi/wiki/Getting-Started-with-NPOI)

1

请查看EasyXLS。它是一个创建xlsx文件的库。

    ExcelDocument workbook = new ExcelDocument(1);

    // Set the sheet name
    workbook.easy_getSheetAt(0).setSheetName("Sheet1");

   // Add data
   ExcelTable xlsTable = ((ExcelWorksheet)workbook.easy_getSheetAt(0)).easy_getExcelTable();
   xlsTable.easy_getCell(0, 0).setValue("ID");
   xlsTable.easy_getCell(0, 1).setValue("Name");
   xlsTable.easy_getCell(1, 0).setValue("1");
   xlsTable.easy_getCell(1, 1).setValue("One");
   xlsTable.easy_getCell(2, 0).setValue("2");
   xlsTable.easy_getCell(2, 1).setValue("Two");

    // Create Excel file
    workbook.easy_WriteXLSXFile("d:\\vdfgdfg.xlsx");

更多内容请参见:
http://www.easyxls.com/manual/basics/create-excel-file.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接