簡體   English   中英

如何在不安裝 Microsoft Office 的情況下在 C# 中創建 Excel(.XLS 和 .XLSX)文件?

[英]How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

如何使用 C# 創建 Excel 電子表格,而無需在運行代碼的機器上安裝 Excel?

您可以使用名為 ExcelLibrary 的庫。 這是一個發布在 Google Code 上的免費開源庫:

Excel庫

這看起來是你上面提到的 PHP ExcelWriter 的一個端口。 它還不會寫入新的 .xlsx 格式,但他們正在努力添加該功能。

它非常簡單、小巧且易於使用。 此外,它還有一個 DataSetHelper,可讓您使用 DataSets 和 DataTables 輕松處理 Excel 數據。

ExcelLibrary 似乎仍然只適用於較舊的 Excel 格式(.xls 文件),但將來可能會增加對較新的 2007/2010 格式的支持。

您還可以使用EPPlus ,它僅適用於 Excel 2007/2010 格式文件(.xlsx 文件)。 還有NPOI可以同時使用。

如評論中所述,每個庫都有一些已知的錯誤。 總而言之,隨着時間的推移,EPPlus 似乎是最好的選擇。 它似乎也更積極地更新和記錄。

此外,正如下面@АртёмЦарионов 所指出的,EPPlus 支持數據透視表,而 ExcelLibrary 可能有一些支持( ExcelLibrary 中的數據透視表問題

這里有幾個鏈接供快速參考:
ExcelLibrary - GNU 小 GPL
EPPlus - GNU (LGPL) - 不再維護
EPPlus 5 - Polyform Noncommercial - 從 2020 年 5 月開始
NPOI - Apache 許可證

這里有一些 ExcelLibrary 的示例代碼:

這是從數據庫中獲取數據並從中創建工作簿的示例。 請注意 ExcelLibrary 代碼是底部的單行:

//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");

//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();

//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();

adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();

//Add the table to the data set
ds.Tables.Add(dt);

//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);

創建 Excel 文件就是這么簡單。 您也可以手動創建 Excel 文件,但上述功能給我留下了深刻的印象。

如果您對 xlsx 格式感到滿意,請嘗試我的 GitHub 項目EPPlus 它從 ExcelPackage 的源開始,但今天完全重寫。 它支持范圍、單元格樣式、圖表、形狀、圖片、命名范圍、自動篩選和許多其他內容。

將 Open XML SDK 2.0 用於 Microsoft Office 怎么樣?

幾個好處:

  • 不需要安裝 Office
  • 由微軟制造 = 體面的 MSDN 文檔
  • 只需一個 .Net dll 即可在項目中使用
  • SDK 附帶了許多工具,如 diff、驗證器等

鏈接:

我成功地使用了以下開源項目:

  • OOXML 格式的 ExcelPackage (Office 2007)

  • .XLS 格式的 NPOI (Office 2003)。 NPOI 2.0 (Beta) 也支持 XLSX。

看看我的博文:

在 C# 中創建 Excel 電子表格 .XLS 和 .XLSX

帶有 Excel 表格和動態圖表的 NPOI

您可以使用 OLEDB 來創建和操作 Excel 文件。 檢查這個: 使用 OLEDB 讀取和寫入 Excel

典型例子:

using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\temp\\test.xls;Extended Properties='Excel 8.0;HDR=Yes'"))
{
  conn.Open();
  OleDbCommand cmd = new OleDbCommand("CREATE TABLE [Sheet1] ([Column1] string, [Column2] string)", conn);
  cmd.ExecuteNonQuery();
}

編輯 - 更多鏈接:

用於.NET的商業解決方案SpreadsheetGear可以做到這一點。

你可以看到現場ASP.NET(C#和VB)樣本這里下載一個評估版本在這里

免責聲明:我擁有 SpreadsheetGear LLC

我使用過的幾個選項:

如果 XLSX 是必須的: ExcelPackage是一個好的開始,但在開發人員停止工作時就消失了。 ExML 從那里開始學習並添加了一些功能。 ExML不是一個糟糕的選擇,我仍在幾個生產網站中使用它。

不過,對於我所有的新項目,我都使用NPOIApache POI的 .NET 端口。 NPOI 2.0 (Alpha)也支持 XLSX。

一個非常輕量級的選擇可能是使用 HTML 表格。 只需在文件中創建 head、body 和 table 標簽,並將其保存為擴展名為 .xls 的文件。 您可以使用 Microsoft 特定的屬性來設置輸出的樣式,包括公式。

我意識到您可能不會在 Web 應用程序中對此進行編碼,但這里是通過 HTML 表組合 Excel 文件的示例 如果您正在編寫控制台應用程序、桌面應用程序或服務,則可以使用此技術。

如果您正在創建 Excel 2007/2010 文件,請嘗試使用此開源項目: https : //github.com/closedxml/closedxml

它提供了一種面向對象的方式來操作文件(類似於 VBA),而無需處理 XML 文檔的麻煩。 它可以被任何 .NET 語言使用,如 C# 和 Visual Basic (VB)。

ClosedXML 允許您在沒有 Excel 應用程序的情況下創建 Excel 2007/2010 文件。 典型示例是在 Web 服務器上創建 Excel 報告:

 var workbook = new XLWorkbook(); var worksheet = workbook.Worksheets.Add("Sample Sheet"); worksheet.Cell("A1").Value = "Hello World!"; workbook.SaveAs("HelloWorld.xlsx");

您實際上可能想查看 C# 中可用的互操作類(例如Microsoft.Office.Interop.Excel 。您說沒有 OLE(這不是),但互操作類非常易於使用。查看C# 文檔此處(Interop for Excel 從 C# PDF 的第 1072 頁開始)。

如果你沒有嘗試過,你可能會印象深刻。

請注意微軟對此的立場

Microsoft 當前不建議也不支持從任何無人參與的非交互式客戶端應用程序或組件(包括 ASP、ASP.NET、DCOM 和 NT 服務)自動化 Microsoft Office 應用程序,因為 Office 可能表現出不穩定的行為和/或在此環境中運行 Office 時出現死鎖。

您可以使用ExcelXmlWriter

它工作正常。

這是一個完全免費的 C# 庫,它允許您使用 OpenXML 庫從DataSetDataTableList<>導出到真正的 Excel 2007 .xlsx 文件中:

http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

提供完整的源代碼 - 免費 - 連同說明和演示應用程序。

將此類添加到您的應用程序后,您只需一行代碼即可將您的數據集導出到 Excel:

CreateExcelFile.CreateExcelDocument(myDataSet, "C:\\Sample.xlsx");

沒有比這更簡單的了...

它甚至不需要在您的服務器上安裝 Excel。

您可以考慮使用XML Spreadsheet 2003格式創建文件。 這是一種使用良好文檔架構的簡單 XML 格式。

您可能想看看GemBox.Spreadsheet

他們有一個具有所有功能的免費版本,但如果符合您的需要,每張紙限制為 150 行,每個工作簿限制為 5 張。

我還沒有需要自己使用它,但看起來確實很有趣。

Syncfusion Essential XlsIO可以做到這一點。 它不依賴於 Microsoft Office,並且對不同平台也有特定的支持。

代碼示例:

//Creates a new instance for ExcelEngine.
ExcelEngine excelEngine = new ExcelEngine();
//Loads or open an existing workbook through Open method of IWorkbooks
IWorkbook workbook = excelEngine.Excel.Workbooks.Open(fileName);
//To-Do some manipulation|
//To-Do some manipulation
//Set the version of the workbook.
workbook.Version = ExcelVersion.Excel2013;
//Save the workbook in file system as xlsx format
workbook.SaveAs(outputFileName);

如果您符合條件(收入低於 100 萬美元),則可以通過社區許可計划免費獲得整套控件。 注意:我為 Syncfusion 工作。

好,

你也可以使用像Aspose這樣的第三方庫。

這個庫的好處是它不需要在你的機器上安裝 Excel,這在你的情況下是理想的。

對於較小的 excel 文件,各種可用的 Office 2003 XML 庫都可以很好地工作。 但是,我發現以 XML 格式保存的大型工作簿的絕對大小是一個問題。 例如,我使用的工作簿在新的(當然壓縮得更緊密)XLSX 格式中是 40MB,變成了 360MB 的 XML 文件。

就我的研究而言,有兩個商業軟件包允許輸出為較舊的二進制文件格式。 他們是:

兩者都不便宜(我認為分別為 500 美元和 800 美元)。 但兩者都獨立於 Excel 本身工作。

我會好奇的是 OpenOffice.org 之類的 Excel 輸出模塊。 我想知道它們是否可以從 Java 移植到 .Net。

我編寫了一個簡單的代碼,通過使用 System.IO.StreamWriter 將數據集導出到 excel 而不使用 excel 對象。

下面是從數據集中讀取所有表並將它們一一寫入工作表的代碼。 我從這篇文章中得到了幫助。

public static void exportToExcel(DataSet source, string fileName)
{
        const string endExcelXML = "</Workbook>";
        const string startExcelXML = "<xml version>\r\n<Workbook " +
                 "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
                 " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
                 "xmlns:x=\"urn:schemas-    microsoft-com:office:" +
                 "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
                 "office:spreadsheet\">\r\n <Styles>\r\n " +
                 "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
                 "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
                 "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
                 "\r\n <Protection/>\r\n </Style>\r\n " +
                 "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
                 "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
                 "<Style     ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
                 " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
                 "ss:ID=\"Decimal\">\r\n <NumberFormat " +
                 "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
                 "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
                 "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
                 "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
                 "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
                 "</Styles>\r\n ";
        System.IO.StreamWriter excelDoc = null;
        excelDoc = new System.IO.StreamWriter(fileName);

        int sheetCount = 1;
        excelDoc.Write(startExcelXML);
        foreach (DataTable table in source.Tables)
        {
            int rowCount = 0;
            excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
            excelDoc.Write("<Table>");
            excelDoc.Write("<Row>");
            for (int x = 0; x < table.Columns.Count; x++)
            {
                excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
                excelDoc.Write(table.Columns[x].ColumnName);
                excelDoc.Write("</Data></Cell>");
            }
            excelDoc.Write("</Row>");
            foreach (DataRow x in table.Rows)
            {
                rowCount++;
                //if the number of rows is > 64000 create a new page to continue output
                if (rowCount == 64000)
                {
                    rowCount = 0;
                    sheetCount++;
                    excelDoc.Write("</Table>");
                    excelDoc.Write(" </Worksheet>");
                    excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
                    excelDoc.Write("<Table>");
                }
                excelDoc.Write("<Row>"); //ID=" + rowCount + "
                for (int y = 0; y < table.Columns.Count; y++)
                {
                    System.Type rowType;
                    rowType = x[y].GetType();
                    switch (rowType.ToString())
                    {
                        case "System.String":
                            string XMLstring = x[y].ToString();
                            XMLstring = XMLstring.Trim();
                            XMLstring = XMLstring.Replace("&", "&");
                            XMLstring = XMLstring.Replace(">", ">");
                            XMLstring = XMLstring.Replace("<", "<");
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                           "<Data ss:Type=\"String\">");
                            excelDoc.Write(XMLstring);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DateTime":
                            //Excel has a specific Date Format of YYYY-MM-DD followed by  
                            //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
                            //The Following Code puts the date stored in XMLDate 
                            //to the format above
                            DateTime XMLDate = (DateTime)x[y];
                            string XMLDatetoString = ""; //Excel Converted Date
                            XMLDatetoString = XMLDate.Year.ToString() +
                                 "-" +
                                 (XMLDate.Month < 10 ? "0" +
                                 XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                                 "-" +
                                 (XMLDate.Day < 10 ? "0" +
                                 XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                                 "T" +
                                 (XMLDate.Hour < 10 ? "0" +
                                 XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                                 ":" +
                                 (XMLDate.Minute < 10 ? "0" +
                                 XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
                                 ":" +
                                 (XMLDate.Second < 10 ? "0" +
                                 XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
                                 ".000";
                            excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
                                         "<Data ss:Type=\"DateTime\">");
                            excelDoc.Write(XMLDatetoString);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Boolean":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                        "<Data ss:Type=\"String\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
                                    "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Decimal":
                        case "System.Double":
                            excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
                                  "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DBNull":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                  "<Data ss:Type=\"String\">");
                            excelDoc.Write("");
                            excelDoc.Write("</Data></Cell>");
                            break;
                        default:
                            throw (new Exception(rowType.ToString() + " not handled."));
                    }
                }
                excelDoc.Write("</Row>");
            }
            excelDoc.Write("</Table>");
            excelDoc.Write(" </Worksheet>");
            sheetCount++;
        }


        excelDoc.Write(endExcelXML);
        excelDoc.Close();
    }

OpenXML 也是一個很好的替代方案,有助於避免在服務器上安裝 MS Excel。Microsoft 提供的 Open XML SDK 2.0 簡化了操作 Open XML 包和包內底層 Open XML 架構元素的任務。 Open XML 應用程序編程接口 (API) 封裝了開發人員在 Open XML 包上執行的許多常見任務。

看看這個OpenXML:有助於避免在服務器上安裝 MS Excel 的替代方案

我最近剛使用FlexCel.NET ,發現它是一個出色的庫! 我不是說太多的軟件產品。 在這里提供整個銷售宣傳毫無意義,您可以閱讀他們網站上的所有功能。

它是一種商業產品,但如果您購買它,您將獲得完整的資源。 所以我想如果你真的想的話,你可以把它編譯到你的程序集中。 否則它只是 xcopy 的一個額外程序集 - 沒有配置或安裝或類似的東西。

我認為如果沒有第三方庫,您將找不到任何方法來做到這一點,因為 .NET 框架顯然沒有內置支持,OLE 自動化只是一個痛苦的世界。

我同意生成 XML 電子表格,這里有一個關於如何為 C# 3 做的例子(每個人都只是在 VB 9 中寫博客:P) http://www.aaron-powell.com/linq-to-xml-to-擅長

只想添加對直接解決您的問題的第三方解決方案的另一個引用: http : //www.officewriter.com

(免責聲明:我為制作 OfficeWriter 的公司 SoftArtisans 工作)

IKVM + POI

或者,您可以使用互操作...

這是一種使用 LINQ to XML 完成此操作的方法,並附有示例代碼:

使用 LINQ to XML 快速導入和導出 Excel 數據

這有點復雜,因為您必須導入命名空間等,但它確實可以讓您避免任何外部依賴項。

(當然,它是 VB .NET,而不是 C#,但您始終可以在自己的項目中隔離 VB .NET 內容以使用 XML 文字,並在 C# 中執行其他所有操作。)

從 C# 創建 Excel 文件的最簡單、最快的方法是使用 Open XML Productivity Tool。 Open XML Productivity Tool 隨 Open XML SDK 安裝一起提供。 該工具將任何 Excel 文件反向工程為 C# 代碼。 然后可以使用 C# 代碼重新生成該文件。

所涉及的過程概述如下:

  1. 使用該工具安裝 Open XML SDK。
  2. 使用具有所需外觀的最新 Excel 客戶端創建 Excel 文件。 將其命名為DesiredLook.xlsx
  3. 使用該工具打開DesiredLook.xlsx並單擊頂部附近的 Reflect Code 按鈕。 在此處輸入圖片說明
  4. 文件的 C# 代碼將在工具的右側窗格中生成。 將此添加到您的 C# 解決方案並生成具有所需外觀的文件。

作為獎勵,此方法適用於任何 Word 和 PowerPoint 文件。 作為 C# 開發人員,您隨后將對代碼進行更改以滿足您的需要。

為此,我 在 github 上開發了一個 簡單的 WPF 應用程序,它將在 Windows 運行。 有一個名為GeneratedClass的占位符類,您可以在其中粘貼生成的代碼。 如果您返回該文件的一個版本,它將生成一個如下所示的 excel 文件:

在此處輸入圖片說明

您可以使用此庫創建格式良好的 Excel 文件: http : //officehelper.codeplex.com/documentation
請參閱以下示例:

using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))
{
    helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;
    helper.CurrentSheetName = "Sheet1";
    helper.CurrentPosition = new CellRef("C3");

    //the template xlsx should contains the named range "header"; use the command "insert"/"name".
    helper.InsertRange("header");

    //the template xlsx should contains the named range "sample1";
    //inside this range you should have cells with these values:
    //<name> , <value> and <comment>, which will be replaced by the values from the getSample()
    CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"}); 
    helper.InsertRange(sample1, getSample());

    //you could use here other named ranges to insert new cells and call InsertRange as many times you want, 
    //it will be copied one after another;
    //even you can change direction or the current cell/sheet before you insert

    //typically you put all your "template ranges" (the names) on the same sheet and then you just delete it
    helper.DeleteSheet("Sheet3");
}        

示例如下所示:

private IEnumerable<List<object>> getSample()
{
    var random = new Random();

    for (int loop = 0; loop < 3000; loop++)
    {
        yield return new List<object> {"test", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop};
    }
}

Infragistics 或 Syncfusion 等一些 3rd 方組件供應商提供了非常好的 Excel 導出功能,不需要安裝 Microsoft Excel。

由於這些供應商還提供高級 UI 網格組件,如果您希望 excel 導出的樣式和布局在應用程序的用戶界面中模擬網格的當前狀態,這些組件將特別方便。

如果您的導出打算在服務器端執行,重點是要導出的數據並且沒有指向 UI 的鏈接,那么我會選擇免費的開源選項之一(例如 ExcelLibrary)。

我以前參與過嘗試在 Microsoft Office 套件上使用服務器端自動化的項目。 基於這種經驗,我強烈建議不要采用這種方法。

public class GridViewExportUtil
{
    public static void Export(string fileName, GridView gv)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader(
            "content-disposition", string.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a form to contain the grid
                Table table = new Table();

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                    table.Rows.Add(gv.HeaderRow);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    GridViewExportUtil.PrepareControlForExport(row);
                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }

                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }

    /// <summary>
    /// Replace any of the contained controls with literals
    /// </summary>
    /// <param name="control"></param>
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }

            if (current.HasControls())
            {
                GridViewExportUtil.PrepareControlForExport(current);
            }
        }
    }
}

嗨,這個解決方案是將您的網格視圖導出到您的 Excel 文件中,它可能對您有所幫助

C# 中一些有用的 Excel 自動化,您可以從以下鏈接中找到。

http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm

博爾頓。

查看示例如何創建 Excel 文件。

C#VB.NET 中有示例

它管理 XSL XSLX 和 CSV Excel 文件。

http://www.devtriogroup.com/ExcelJetcell/Samples

Java 開源解決方案是Apache POI 也許有一種方法可以在這里設置互操作,但我對 Java 的了解不夠,無法回答這個問題。

當我探索這個問題時,我最終使用了 Interop 程序集。

你試過 sylk 嗎?

我們曾經在經典 asp 中生成 excelsheets 作為 sylk,現在我們也在尋找一個 excelgenerator。

sylk 的優點是,您可以格式化單元格。

您可以使用 Excel XML 格式將其寫成 XML,並使用 .XLS 擴展名命名,它將以 excel 打開。 您可以控制 XML 文件標題中的所有格式(粗體、寬度等)。

有一個來自 Wikipedia示例 XML

我也投票給GemBox.Spreadsheet

非常快速且易於使用,其網站上有大量示例。

將我的報告任務提升到一個全新的執行速度水平。

一個經常被忽視的非常簡單的選項是使用Microsoft Reporting創建一個 .rdlc 報告並將其導出為 excel 格式。 您可以在 Visual Studio 中設計它並使用以下方法生成文件:

localReport.Render("EXCELOPENXML", null, ((name, ext, encoding, mimeType, willSeek) => stream = new FileStream(name, FileMode.CreateNew)), out warnings);

您還可以將其導出為 .doc 或 .pdf,分別使用"WORDOPENXML""PDF" ,並且它在許多不同的平台上都受支持,例如 ASP.NET 和 SSRS。

在可以查看結果的可視化設計器中進行更改要容易得多,相信我,一旦您開始對數據進行分組、格式化組標題、添加新部分,您就不會想弄亂數十個 XML 節點。

你可以試試我的SwiftExcel庫。 這個庫直接寫入文件,所以效率很高。 例如,您可以在幾秒鍾內寫入 100k 行而無需任何內存使用。

下面是一個簡單的用法示例:

using (var ew = new ExcelWriter("C:\\temp\\test.xlsx"))
{
    for (var row = 1; row <= 10; row++)
    {
        for (var col = 1; col <= 5; col++)
        {
            ew.Write($"row:{row}-col:{col}", col, row);
        }
    }
}

http://www.codeproject.com/KB/cs/Excel_and_C_.aspx <= 為什么不直接使用 Windows 的內置功能,只需在服務器上安裝 office,您安裝的任何應用程序都可以自動化。

只需使用本機方法就容易多了。

如果安裝了它,您就可以使用它,這是 Windows 中最棒但未使用的功能,它在過去被稱為 COM,它為您節省了大量時間和痛苦。

或者更簡單,只需使用 ref lib MS 用品 - http://csharp.net-informations.com/excel/csharp-create-excel.htm

如何在不安裝 Microsoft Office 的情況下在 OneDrive 上使用 C# 創建 Excel (.xslx) 文件

Microsoft Graph API提供文件和 Excel API,用於為企業和消費者帳戶創建和修改存儲在 OneDrive 中的 Excel 文件。 Microsoft.Graph NuGet 包提供了許多用於處理 File 和 Excel API 的接口。

{
  Name = "myExcelFile.xslx",
  File = new Microsoft.Graph.File()
};

// Create an empty file in the user's OneDrive.
var excelWorkbookDriveItem = await graphClient.Me.Drive.Root.Children.Request().AddAsync(excelWorkbook);

// Add the contents of a template Excel file.
DriveItem excelDriveItem;
using (Stream ms = ResourceHelper.GetResourceAsStream(ResourceHelper.ExcelTestResource))
{
    //Upload content to the file. ExcelTestResource is an empty template Excel file.
    //https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_uploadcontent
    excelDriveItem = await graphClient.Me.Drive.Items[excelWorkbookDriveItem.Id].Content.Request().PutAsync<DriveItem>(ms);
}

此時,您現在已經在用戶(企業或消費者)或組的 OneDrive 中創建了一個 Excel 文件。 您現在可以使用Excel API更改 Excel 文件,而無需使用 Excel,也無需了解 Excel XML 格式

您可以在 Visual Studio 上安裝 OpenXml nuget 包。 這是將數據表導出到excel文件的一些代碼:

Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Spreadsheet

Public Class ExportExcelClass
    Public Sub New()

    End Sub

    Public Sub ExportDataTable(ByVal table As DataTable, ByVal exportFile As String)
        ' Create a spreadsheet document by supplying the filepath.
        ' By default, AutoSave = true, Editable = true, and Type = xlsx.
        Dim spreadsheetDocument As SpreadsheetDocument = spreadsheetDocument.Create(exportFile, SpreadsheetDocumentType.Workbook)

        ' Add a WorkbookPart to the document.
        Dim workbook As WorkbookPart = spreadsheetDocument.AddWorkbookPart
        workbook.Workbook = New Workbook

        ' Add a WorksheetPart to the WorkbookPart.
        Dim Worksheet As WorksheetPart = workbook.AddNewPart(Of WorksheetPart)()
        Worksheet.Worksheet = New Worksheet(New SheetData())

        ' Add Sheets to the Workbook.
        Dim sheets As Sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(Of Sheets)(New Sheets())

        Dim data As SheetData = Worksheet.Worksheet.GetFirstChild(Of SheetData)()
        Dim Header As Row = New Row()
        Header.RowIndex = CType(1, UInt32)

        For Each column As DataColumn In table.Columns
            Dim headerCell As Cell = createTextCell(table.Columns.IndexOf(column) + 1, 1, column.ColumnName)
            Header.AppendChild(headerCell)
        Next

        data.AppendChild(Header)

        Dim contentRow As DataRow
        For i As Integer = 0 To table.Rows.Count - 1
            contentRow = table.Rows(i)
            data.AppendChild(createContentRow(contentRow, i + 2))
        Next

    End Sub

    Private Function createTextCell(ByVal columnIndex As Integer, ByVal rowIndex As Integer, ByVal cellValue As Object) As Cell
        Dim cell As Cell = New Cell()
        cell.DataType = CellValues.InlineString

        cell.CellReference = getColumnName(columnIndex) + rowIndex.ToString

        Dim inlineString As InlineString = New InlineString()
        Dim t As Text = New Text()
        t.Text = cellValue.ToString()
        inlineString.AppendChild(t)
        cell.AppendChild(inlineString)
        Return cell
    End Function

    Private Function createContentRow(ByVal dataRow As DataRow, ByVal rowIndex As Integer) As Row
        Dim row As Row = New Row With {
            .rowIndex = CType(rowIndex, UInt32)
        }

        For i As Integer = 0 To dataRow.Table.Columns.Count - 1
            Dim dataCell As Cell = createTextCell(i + 1, rowIndex, dataRow(i))
            row.AppendChild(dataCell)
        Next

        Return row
    End Function

    Private Function getColumnName(ByVal columnIndex As Integer) As String
        Dim dividend As Integer = columnIndex
        Dim columnName As String = String.Empty
        Dim modifier As Integer

        While dividend > 0
            modifier = (dividend - 1) Mod 26
            columnName = Convert.ToChar(65 + modifier).ToString() & columnName
            dividend = CInt(((dividend - modifier) / 26))
        End While

        Return columnName
    End Function
End Class

我再次重新編碼代碼,現在您可以創建一個 .xls 文件,稍后您可以轉換為 Excel 2003 Open XML 格式。

private static void exportToExcel(DataSet source, string fileName)
    {
        // Documentacion en:
        // https://en.wikipedia.org/wiki/Microsoft_Office_XML_formats
        // https://answers.microsoft.com/en-us/msoffice/forum/all/how-to-save-office-ms-xml-as-xlsx-file/4a77dae5-6855-457d-8359-e7b537beb1db
        // https://riptutorial.com/es/openxml

        const string startExcelXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"+
                 "<?mso-application progid=\"Excel.Sheet\"?>\r\n" +
                 "<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
                 "xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
                 "xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\n " +
                 "xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n " +
                 "xmlns:html=\"http://www.w3.org/TR/REC-html40\">\r\n " +
                 "xmlns:html=\"https://www.w3.org/TR/html401/\">\r\n " +

                 "<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">\r\n " +
                 "  <Version>16.00</Version>\r\n " +
                 "</DocumentProperties>\r\n " +
                 " <OfficeDocumentSettings xmlns=\"urn:schemas-microsoft-com:office:office\">\r\n " +
                 "  <AllowPNG/>\r\n " +
                 " </OfficeDocumentSettings>\r\n " +

                 " <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n " +
                 "  <WindowHeight>9750</WindowHeight>\r\n " +
                 "  <WindowWidth>24000</WindowWidth>\r\n " +
                 "  <WindowTopX>0</WindowTopX>\r\n " +
                 "  <WindowTopY>0</WindowTopY>\r\n " +
                 "  <RefModeR1C1/>\r\n " +
                 "  <ProtectStructure>False</ProtectStructure>\r\n " +
                 "  <ProtectWindows>False</ProtectWindows>\r\n " +
                 " </ExcelWorkbook>\r\n " +

                 "<Styles>\r\n " +
                 "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
                 "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
                 "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
                 "\r\n <Protection/>\r\n </Style>\r\n " +
                 "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
                 "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
                 "<Style ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
                 " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
                 "ss:ID=\"Decimal\">\r\n <NumberFormat " +
                 "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
                 "<Style ss:ID=\"Integer\">\r\n <NumberFormat/>" +
                 "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
                 "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
                 "ss:Format=\"dd/mm/yyyy;@\"/>\r\n </Style>\r\n " +
                 "</Styles>\r\n ";
        System.IO.StreamWriter excelDoc = null;
        excelDoc = new System.IO.StreamWriter(fileName,false);

        int sheetCount = 1;
        excelDoc.Write(startExcelXML);
        foreach (DataTable table in source.Tables)
        {
            int rowCount = 0;
            excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
            excelDoc.Write("<Table>");
            excelDoc.Write("<Row>");
            for (int x = 0; x < table.Columns.Count; x++)
            {
                excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
                excelDoc.Write(table.Columns[x].ColumnName);
                excelDoc.Write("</Data></Cell>");
            }
            excelDoc.Write("</Row>");
            foreach (DataRow x in table.Rows)
            {
                rowCount++;
                //if the number of rows is > 64000 create a new page to continue output
                if (rowCount == 1048576)
                {
                    rowCount = 0;
                    sheetCount++;
                    excelDoc.Write("</Table>");
                    excelDoc.Write(" </Worksheet>");
                    excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
                    excelDoc.Write("<Table>");
                }
                excelDoc.Write("<Row>"); //ID=" + rowCount + "
                for (int y = 0; y < table.Columns.Count; y++)
                {
                    System.Type rowType;
                    rowType = x[y].GetType();
                    switch (rowType.ToString())
                    {
                        case "System.String":
                            string XMLstring = x[y].ToString();
                            XMLstring = XMLstring.Trim();
                            XMLstring = XMLstring.Replace("&", "&");
                            XMLstring = XMLstring.Replace(">", ">");
                            XMLstring = XMLstring.Replace("<", "<");
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                           "<Data ss:Type=\"String\">");
                            excelDoc.Write(XMLstring);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DateTime":
                            //Excel has a specific Date Format of YYYY-MM-DD followed by  
                            //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
                            //The Following Code puts the date stored in XMLDate 
                            //to the format above
                            DateTime XMLDate = (DateTime)x[y];
                            string XMLDatetoString = ""; //Excel Converted Date
                            XMLDatetoString = XMLDate.Year.ToString() +
                                 "-" +
                                 (XMLDate.Month < 10 ? "0" +
                                 XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                                 "-" +
                                 (XMLDate.Day < 10 ? "0" +
                                 XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                                 "T" +
                                 (XMLDate.Hour < 10 ? "0" +
                                 XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                                 ":" +
                                 (XMLDate.Minute < 10 ? "0" +
                                 XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
                                 ":" +
                                 (XMLDate.Second < 10 ? "0" +
                                 XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
                                 ".000";
                            excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
                                         "<Data ss:Type=\"DateTime\">");
                            excelDoc.Write(XMLDatetoString);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Boolean":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                        "<Data ss:Type=\"String\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
                                    "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Decimal":
                        case "System.Double":
                            excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
                                  "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DBNull":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                  "<Data ss:Type=\"String\">");
                            excelDoc.Write("");
                            excelDoc.Write("</Data></Cell>");
                            break;
                        default:
                            throw (new Exception(rowType.ToString() + " not handled."));
                    }
                }
                excelDoc.Write("</Row>");
            }
            excelDoc.Write("</Table>");
            excelDoc.Write("</Worksheet>");               
            sheetCount++;
        }

        const string endExcelOptions1 = "\r\n<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n" +
            "<Selected/>\r\n" +
            "<ProtectObjects>False</ProtectObjects>\r\n" +
            "<ProtectScenarios>False</ProtectScenarios>\r\n" +
            "</WorksheetOptions>\r\n";

        excelDoc.Write(endExcelOptions1);
        excelDoc.Write("</Workbook>");
        excelDoc.Close();
    }

如果您從代碼制作數據表或數據網格視圖,您可以使用這種簡單的方法保存所有數據。不推薦使用這種方法,但即使您沒有在計算機中安裝 MS Excel,它也能 100% 工作。

try
 {
  SaveFileDialog saveFileDialog1 = new SaveFileDialog();
  saveFileDialog1.Filter = "Excel Documents (*.xls)|*.xls";
  saveFileDialog1.FileName = "Employee Details.xls";
  if (saveFileDialog1.ShowDialog() == DialogResult.OK)
  {
  string fname = saveFileDialog1.FileName;
  StreamWriter wr = new StreamWriter(fname);
  for (int i = 0; i <DataTable.Columns.Count; i++)
  {
  wr.Write(DataTable.Columns[i].ToString().ToUpper() + "\t");
  }
  wr.WriteLine();

  //write rows to excel file
  for (int i = 0; i < (DataTable.Rows.Count); i++)
  {
  for (int j = 0; j < DataTable.Columns.Count; j++)
  {
  if (DataTable.Rows[i][j] != null)
  {
  wr.Write(Convert.ToString(getallData.Rows[i][j]) + "\t");
  }
   else
   {
   wr.Write("\t");
   }
   }
   //go to next line
   wr.WriteLine();
   }
   //close file
   wr.Close();
   }
   }
   catch (Exception)
   {
    MessageBox.Show("Error Create Excel Sheet!");
   }

前段時間,我在 NPOI 之上創建了一個 DLL。 使用它非常簡單:

IList<DummyPerson> dummyPeople = new List<DummyPerson>();
//Add data to dummyPeople...
IExportEngine engine = new ExcelExportEngine();
engine.AddData(dummyPeople); 
MemoryStream memory = engine.Export();

您可以在此處閱讀更多相關信息。

順便說一下,是 100% 開源的。 隨意使用、編輯和分享;)

要將 xls 保存為 xlsx 格式,我們只需要從Microsoft.Office.Interop.Excel庫中調用SaveAs方法。 此方法將需要大約 16 個參數,其中之一也是文件格式。

Microsoft 文檔:此處為SaveAs 方法參數

我們需要傳遞的對象就像

wb.SaveAs(filename, 51, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, false, false, 1,1, true, 
System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value)

這里,51 是 XLSX 的枚舉值

對於不同文件格式的另存為,您可以參考xlFileFormat

我想知道為什么沒有人建議使用免費的 ImportExcel 模塊使用 PowerShell; 它可以輕松創建 XML-Excel 文件 (xlsx)。

創建來自 SQL Server 等數據庫的 Excel 工作表時尤其容易...

在我的項目中,我使用了一些 .net 庫來提取 Excel 文件(.xls 和 .xlsx)

為了導出數據,我經常使用rdlc

要修改我使用的 excel 文件(嘗試設置空白單元格 A15 時的示例代碼):

封閉的XML

        //Closed XML
        var workbook = new XLWorkbook(sUrlFile); // load the existing excel file
        var worksheet = workbook.Worksheets.Worksheet(1);
        worksheet.Cell("A15").SetValue("");
        workbook.Save();

IronXL

       string sUrlFile = "G:\\ReportAmortizedDetail.xls";
        WorkBook workbook = WorkBook.Load(sUrlFile);
        WorkSheet sheet = workbook.WorkSheets.First();
        //Select cells easily in Excel notation and return the calculated value
        sheet["A15"].First().Value = "";
        sheet["A15"].First().FormatString = "";

        workbook.Save();
        workbook.Close();
        workbook = null;

SpireXLS (當我嘗試時,圖書館打印附加表以提供我們使用試用圖書館的信息

            string sUrlFile = "G:\\ReportAmortizedDetail.xls";
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(sUrlFile);
            //Get the 1st sheet
            Worksheet sheet = workbook.Worksheets[0];
            //Specify the cell range
            CellRange range = sheet.Range["A15"];
            //Find all matched text in the range
            CellRange[] cells = range.FindAllString("hi", false, false);
            //Replace text
            foreach (CellRange cell in range)
            {
                cell.Text = "";
            }
            //Save
            workbook.Save();

傑特·奧爾德布

    //ExcelTool Class
    public static int ExcelUpdateSheets(string path, string sWorksheetName, string sCellLocation, string sValue)
    {
        int iResult = -99;
        String sConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO'";
        OleDbConnection objConn = new OleDbConnection(sConnectionString);
        objConn.Open();
        OleDbCommand objCmdSelect = new OleDbCommand("UPDATE [" + sWorksheetName + "$" + sCellLocation + "] SET F1=" + UtilityClass.ValueSQL(sValue), objConn);
        objCmdSelect.ExecuteNonQuery();
        objConn.Close();

        return iResult;
    }

用法 :

    ExcelTool.ExcelUpdateSheets(sUrlFile, "ReportAmortizedDetail", "A15:A15", "");

Aspose

            var workbook = new Aspose.Cells.Workbook(sUrlFile);
            // access first (default) worksheet
            var sheet = workbook.Worksheets[0];
            // access CellsCollection of first worksheet
            var cells = sheet.Cells;
            // write HelloWorld to cells A1
            cells["A15"].Value = "";
            // save spreadsheet to disc
            workbook.Save(sUrlFile);
            workbook.Dispose();
            workbook = null;

我找到了另一個沒有太多依賴的庫: MiniExcel

您可以使用DataTable創建一個DataSet作為電子表格(表的名稱是電子表格的名稱)並將其保存到.xlsx文件中

using var stream = File.Create(filePath);
stream.SaveAs(dataSet);

或者

MiniExcel.SaveAs(filePath, dataSet);

它還提供讀取 Excel 個文件,並支持讀取和寫入 CSV 個文件。

這是創建 Excel 文件的最簡單方法。

擴展名為 .xlsx 的 Excel 文件是包含 .XML 文件的壓縮文件夾 - 但很復雜。

首先創建文件夾結構如下 -

public class CreateFileOrFolder
{
    static void Main()
    {
        //
        // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-create-a-file-or-folder
        //
        // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file
        //
        // .NET Framework 4.7.2
        //
        // Specify a name for your top-level folder.
        string folderName = @"C:\Users\david\Desktop\Book3";

        // To create a string that specifies the path to a subfolder under your
        // top-level folder, add a name for the subfolder to folderName.

        string pathString = System.IO.Path.Combine(folderName, "_rels");
        System.IO.Directory.CreateDirectory(pathString);
        pathString = System.IO.Path.Combine(folderName, "docProps");
        System.IO.Directory.CreateDirectory(pathString);
        pathString = System.IO.Path.Combine(folderName, "xl");
        System.IO.Directory.CreateDirectory(pathString);

        string subPathString = System.IO.Path.Combine(pathString, "_rels");
        System.IO.Directory.CreateDirectory(subPathString);
        subPathString = System.IO.Path.Combine(pathString, "theme");
        System.IO.Directory.CreateDirectory(subPathString);
        subPathString = System.IO.Path.Combine(pathString, "worksheets");
        System.IO.Directory.CreateDirectory(subPathString);
        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}

接下來,創建文本文件來保存描述 Excel 電子表格所需的 XML。

namespace MakeFiles3
{
    class Program
    {
        static void Main(string[] args)
        {
            //
            // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file
            //
            // .NET Framework 4.7.2
            //
            string fileName = @"C:\Users\david\Desktop\Book3\_rels\.rels";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\docProps\app.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\docProps\core.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\_rels\workbook.xml.rels";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\theme\theme1.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\worksheets\sheet1.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\styles.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\workbook.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\[Content_Types].xml";
            fnWriteFile(fileName);
            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();

            bool fnWriteFile(string strFilePath)
            {
                if (!System.IO.File.Exists(strFilePath))
                {
                    using (System.IO.FileStream fs = System.IO.File.Create(strFilePath))
                    {
                        return true;
                    }
                }
                else
                {
                    System.Console.WriteLine("File \"{0}\" already exists.", strFilePath);
                    return false;
                }
            }
        }
    }
}

接下來用 XML 填充文本文件。

所需的 XML 相當冗長,因此您可能需要使用此 github 存儲庫。

https://github.com/DaveTallett26/MakeFiles4/blob/master/MakeFiles4/Program.cs

//
// https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file
// .NET Framework 4.7.2
//
using System.IO;

namespace MakeFiles4
{
    class Program
    {
        static void Main(string[] args)
        {
            string xContents = @"a";
            string xFilename = @"a";
            xFilename = @"C:\Users\david\Desktop\Book3\[Content_Types].xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Types xmlns=""http://schemas.openxmlformats.org/package/2006/content-types""><Default Extension=""rels"" ContentType=""application/vnd.openxmlformats-package.relationships+xml""/><Default Extension=""xml"" ContentType=""application/xml""/><Override PartName=""/xl/workbook.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml""/><Override PartName=""/xl/worksheets/sheet1.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml""/><Override PartName=""/xl/theme/theme1.xml"" ContentType=""application/vnd.openxmlformats-officedocument.theme+xml""/><Override PartName=""/xl/styles.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml""/><Override PartName=""/docProps/core.xml"" ContentType=""application/vnd.openxmlformats-package.core-properties+xml""/><Override PartName=""/docProps/app.xml"" ContentType=""application/vnd.openxmlformats-officedocument.extended-properties+xml""/></Types>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\_rels\.rels";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Relationships xmlns=""http://schemas.openxmlformats.org/package/2006/relationships""><Relationship Id=""rId3"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"" Target=""docProps/app.xml""/><Relationship Id=""rId2"" Type=""http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"" Target=""docProps/core.xml""/><Relationship Id=""rId1"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"" Target=""xl/workbook.xml""/></Relationships>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\docProps\app.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Properties xmlns=""http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"" xmlns:vt=""http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes""><Application>Microsoft Excel</Application><DocSecurity>0</DocSecurity><ScaleCrop>false</ScaleCrop><HeadingPairs><vt:vector size=""2"" baseType=""variant""><vt:variant><vt:lpstr>Worksheets</vt:lpstr></vt:variant><vt:variant><vt:i4>1</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size=""1"" baseType=""lpstr""><vt:lpstr>Sheet1</vt:lpstr></vt:vector></TitlesOfParts><Company></Company><LinksUpToDate>false</LinksUpToDate><SharedDoc>false</SharedDoc><HyperlinksChanged>false</HyperlinksChanged><AppVersion>16.0300</AppVersion></Properties>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\docProps\core.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><cp:coreProperties xmlns:cp=""http://schemas.openxmlformats.org/package/2006/metadata/core-properties"" xmlns:dc=""http://purl.org/dc/elements/1.1/"" xmlns:dcterms=""http://purl.org/dc/terms/"" xmlns:dcmitype=""http://purl.org/dc/dcmitype/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""><dc:creator>David Tallett</dc:creator><cp:lastModifiedBy>David Tallett</cp:lastModifiedBy><dcterms:created xsi:type=""dcterms:W3CDTF"">2021-10-26T15:47:15Z</dcterms:created><dcterms:modified xsi:type=""dcterms:W3CDTF"">2021-10-26T15:47:35Z</dcterms:modified></cp:coreProperties>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\styles.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><styleSheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x14ac x16r2 xr"" xmlns:x14ac=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"" xmlns:x16r2=""http://schemas.microsoft.com/office/spreadsheetml/2015/02/main"" xmlns:xr=""http://schemas.microsoft.com/office/spreadsheetml/2014/revision""><fonts count=""1"" x14ac:knownFonts=""1""><font><sz val=""11""/><color theme=""1""/><name val=""Calibri""/><family val=""2""/><scheme val=""minor""/></font></fonts><fills count=""2""><fill><patternFill patternType=""none""/></fill><fill><patternFill patternType=""gray125""/></fill></fills><borders count=""1""><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count=""1""><xf numFmtId=""0"" fontId=""0"" fillId=""0"" borderId=""0""/></cellStyleXfs><cellXfs count=""1""><xf numFmtId=""0"" fontId=""0"" fillId=""0"" borderId=""0"" xfId=""0""/></cellXfs><cellStyles count=""1""><cellStyle name=""Normal"" xfId=""0"" builtinId=""0""/></cellStyles><dxfs count=""0""/><tableStyles count=""0"" defaultTableStyle=""TableStyleMedium2"" defaultPivotStyle=""PivotStyleLight16""/><extLst><ext uri=""{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"" xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main""><x14:slicerStyles defaultSlicerStyle=""SlicerStyleLight1""/></ext><ext uri=""{9260A510-F301-46a8-8635-F512D64BE5F5}"" xmlns:x15=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/main""><x15:timelineStyles defaultTimelineStyle=""TimeSlicerStyleLight1""/></ext></extLst></styleSheet>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\workbook.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x15 xr xr6 xr10 xr2"" xmlns:x15=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"" xmlns:xr=""http://schemas.microsoft.com/office/spreadsheetml/2014/revision"" xmlns:xr6=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision6"" xmlns:xr10=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision10"" xmlns:xr2=""http://schemas.microsoft.com/office/spreadsheetml/2015/revision2""><fileVersion appName=""xl"" lastEdited=""7"" lowestEdited=""7"" rupBuild=""24430""/><workbookPr defaultThemeVersion=""166925""/><mc:AlternateContent xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006""><mc:Choice Requires=""x15""><x15ac:absPath url=""C:\Users\david\Desktop\"" xmlns:x15ac=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/ac""/></mc:Choice></mc:AlternateContent><xr:revisionPtr revIDLastSave=""0"" documentId=""8_{C633700D-2D40-49EE-8C5E-2561E28A6758}"" xr6:coauthVersionLast=""47"" xr6:coauthVersionMax=""47"" xr10:uidLastSave=""{00000000-0000-0000-0000-000000000000}""/><bookViews><workbookView xWindow=""-120"" yWindow=""-120"" windowWidth=""29040"" windowHeight=""15840"" xr2:uid=""{934C5B62-1DC1-4322-BAE8-00D615BD2FB3}""/></bookViews><sheets><sheet name=""Sheet1"" sheetId=""1"" r:id=""rId1""/></sheets><calcPr calcId=""191029""/><extLst><ext uri=""{140A7094-0E35-4892-8432-C4D2E57EDEB5}"" xmlns:x15=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/main""><x15:workbookPr chartTrackingRefBase=""1""/></ext><ext uri=""{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}"" xmlns:xcalcf=""http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures""><xcalcf:calcFeatures><xcalcf:feature name=""microsoft.com:RD""/><xcalcf:feature name=""microsoft.com:Single""/><xcalcf:feature name=""microsoft.com:FV""/><xcalcf:feature name=""microsoft.com:CNMTM""/><xcalcf:feature name=""microsoft.com:LET_WF""/></xcalcf:calcFeatures></ext></extLst></workbook>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\_rels\workbook.xml.rels";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Relationships xmlns=""http://schemas.openxmlformats.org/package/2006/relationships""><Relationship Id=""rId3"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"" Target=""styles.xml""/><Relationship Id=""rId2"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"" Target=""theme/theme1.xml""/><Relationship Id=""rId1"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"" Target=""worksheets/sheet1.xml""/></Relationships>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\theme\theme1.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><a:theme xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" name=""Office Theme""><a:themeElements><a:clrScheme name=""Office""><a:dk1><a:sysClr val=""windowText"" lastClr=""000000""/></a:dk1><a:lt1><a:sysClr val=""window"" lastClr=""FFFFFF""/></a:lt1><a:dk2><a:srgbClr val=""44546A""/></a:dk2><a:lt2><a:srgbClr val=""E7E6E6""/></a:lt2><a:accent1><a:srgbClr val=""4472C4""/></a:accent1><a:accent2><a:srgbClr val=""ED7D31""/></a:accent2><a:accent3><a:srgbClr val=""A5A5A5""/></a:accent3><a:accent4><a:srgbClr val=""FFC000""/></a:accent4><a:accent5><a:srgbClr val=""5B9BD5""/></a:accent5><a:accent6><a:srgbClr val=""70AD47""/></a:accent6><a:hlink><a:srgbClr val=""0563C1""/></a:hlink><a:folHlink><a:srgbClr val=""954F72""/></a:folHlink></a:clrScheme><a:fontScheme name=""Office""><a:majorFont><a:latin typeface=""Calibri Light"" panose=""020F0302020204030204""/><a:ea typeface=""""/><a:cs typeface=""""/><a:font script=""Jpan"" typeface=""游ゴシック Light""/><a:font script=""Hang"" typeface=""맑은 고딕""/><a:font script=""Hans"" typeface=""等線 Light""/><a:font script=""Hant"" typeface=""新細明體""/><a:font script=""Arab"" typeface=""Times New Roman""/><a:font script=""Hebr"" typeface=""Times New Roman""/><a:font script=""Thai"" typeface=""Tahoma""/><a:font script=""Ethi"" typeface=""Nyala""/><a:font script=""Beng"" typeface=""Vrinda""/><a:font script=""Gujr"" typeface=""Shruti""/><a:font script=""Khmr"" typeface=""MoolBoran""/><a:font script=""Knda"" typeface=""Tunga""/><a:font script=""Guru"" typeface=""Raavi""/><a:font script=""Cans"" typeface=""Euphemia""/><a:font script=""Cher"" typeface=""Plantagenet Cherokee""/><a:font script=""Yiii"" typeface=""Microsoft Yi Baiti""/><a:font script=""Tibt"" typeface=""Microsoft Himalaya""/><a:font script=""Thaa"" typeface=""MV Boli""/><a:font script=""Deva"" typeface=""Mangal""/><a:font script=""Telu"" typeface=""Gautami""/><a:font script=""Taml"" typeface=""Latha""/><a:font script=""Syrc"" typeface=""Estrangelo Edessa""/><a:font script=""Orya"" typeface=""Kalinga""/><a:font script=""Mlym"" typeface=""Kartika""/><a:font script=""Laoo"" typeface=""DokChampa""/><a:font script=""Sinh"" typeface=""Iskoola Pota""/><a:font script=""Mong"" typeface=""Mongolian Baiti""/><a:font script=""Viet"" typeface=""Times New Roman""/><a:font script=""Uigh"" typeface=""Microsoft Uighur""/><a:font script=""Geor"" typeface=""Sylfaen""/><a:font script=""Armn"" typeface=""Arial""/><a:font script=""Bugi"" typeface=""Leelawadee UI""/><a:font script=""Bopo"" typeface=""Microsoft JhengHei""/><a:font script=""Java"" typeface=""Javanese Text""/><a:font script=""Lisu"" typeface=""Segoe UI""/><a:font script=""Mymr"" typeface=""Myanmar Text""/><a:font script=""Nkoo"" typeface=""Ebrima""/><a:font script=""Olck"" typeface=""Nirmala UI""/><a:font script=""Osma"" typeface=""Ebrima""/><a:font script=""Phag"" typeface=""Phagspa""/><a:font script=""Syrn"" typeface=""Estrangelo Edessa""/><a:font script=""Syrj"" typeface=""Estrangelo Edessa""/><a:font script=""Syre"" typeface=""Estrangelo Edessa""/><a:font script=""Sora"" typeface=""Nirmala UI""/><a:font script=""Tale"" typeface=""Microsoft Tai Le""/><a:font script=""Talu"" typeface=""Microsoft New Tai Lue""/><a:font script=""Tfng"" typeface=""Ebrima""/></a:majorFont><a:minorFont><a:latin typeface=""Calibri"" panose=""020F0502020204030204""/><a:ea typeface=""""/><a:cs typeface=""""/><a:font script=""Jpan"" typeface=""游ゴシック""/><a:font script=""Hang"" typeface=""맑은 고딕""/><a:font script=""Hans"" typeface=""等線""/><a:font script=""Hant"" typeface=""新細明體""/><a:font script=""Arab"" typeface=""Arial""/><a:font script=""Hebr"" typeface=""Arial""/><a:font script=""Thai"" typeface=""Tahoma""/><a:font script=""Ethi"" typeface=""Nyala""/><a:font script=""Beng"" typeface=""Vrinda""/><a:font script=""Gujr"" typeface=""Shruti""/><a:font script=""Khmr"" typeface=""DaunPenh""/><a:font script=""Knda"" typeface=""Tunga""/><a:font script=""Guru"" typeface=""Raavi""/><a:font script=""Cans"" typeface=""Euphemia""/><a:font script=""Cher"" typeface=""Plantagenet Cherokee""/><a:font script=""Yiii"" typeface=""Microsoft Yi Baiti""/><a:font script=""Tibt"" typeface=""Microsoft Himalaya""/><a:font script=""Thaa"" typeface=""MV Boli""/><a:font script=""Deva"" typeface=""Mangal""/><a:font script=""Telu"" typeface=""Gautami""/><a:font script=""Taml"" typeface=""Latha""/><a:font script=""Syrc"" typeface=""Estrangelo Edessa""/><a:font script=""Orya"" typeface=""Kalinga""/><a:font script=""Mlym"" typeface=""Kartika""/><a:font script=""Laoo"" typeface=""DokChampa""/><a:font script=""Sinh"" typeface=""Iskoola Pota""/><a:font script=""Mong"" typeface=""Mongolian Baiti""/><a:font script=""Viet"" typeface=""Arial""/><a:font script=""Uigh"" typeface=""Microsoft Uighur""/><a:font script=""Geor"" typeface=""Sylfaen""/><a:font script=""Armn"" typeface=""Arial""/><a:font script=""Bugi"" typeface=""Leelawadee UI""/><a:font script=""Bopo"" typeface=""Microsoft JhengHei""/><a:font script=""Java"" typeface=""Javanese Text""/><a:font script=""Lisu"" typeface=""Segoe UI""/><a:font script=""Mymr"" typeface=""Myanmar Text""/><a:font script=""Nkoo"" typeface=""Ebrima""/><a:font script=""Olck"" typeface=""Nirmala UI""/><a:font script=""Osma"" typeface=""Ebrima""/><a:font script=""Phag"" typeface=""Phagspa""/><a:font script=""Syrn"" typeface=""Estrangelo Edessa""/><a:font script=""Syrj"" typeface=""Estrangelo Edessa""/><a:font script=""Syre"" typeface=""Estrangelo Edessa""/><a:font script=""Sora"" typeface=""Nirmala UI""/><a:font script=""Tale"" typeface=""Microsoft Tai Le""/><a:font script=""Talu"" typeface=""Microsoft New Tai Lue""/><a:font script=""Tfng"" typeface=""Ebrima""/></a:minorFont></a:fontScheme><a:fmtScheme name=""Office""><a:fillStyleLst><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:gradFill rotWithShape=""1""><a:gsLst><a:gs pos=""0""><a:schemeClr val=""phClr""><a:lumMod val=""110000""/><a:satMod val=""105000""/><a:tint val=""67000""/></a:schemeClr></a:gs><a:gs pos=""50000""><a:schemeClr val=""phClr""><a:lumMod val=""105000""/><a:satMod val=""103000""/><a:tint val=""73000""/></a:schemeClr></a:gs><a:gs pos=""100000""><a:schemeClr val=""phClr""><a:lumMod val=""105000""/><a:satMod val=""109000""/><a:tint val=""81000""/></a:schemeClr></a:gs></a:gsLst><a:lin ang=""5400000"" scaled=""0""/></a:gradFill><a:gradFill rotWithShape=""1""><a:gsLst><a:gs pos=""0""><a:schemeClr val=""phClr""><a:satMod val=""103000""/><a:lumMod val=""102000""/><a:tint val=""94000""/></a:schemeClr></a:gs><a:gs pos=""50000""><a:schemeClr val=""phClr""><a:satMod val=""110000""/><a:lumMod val=""100000""/><a:shade val=""100000""/></a:schemeClr></a:gs><a:gs pos=""100000""><a:schemeClr val=""phClr""><a:lumMod val=""99000""/><a:satMod val=""120000""/><a:shade val=""78000""/></a:schemeClr></a:gs></a:gsLst><a:lin ang=""5400000"" scaled=""0""/></a:gradFill></a:fillStyleLst><a:lnStyleLst><a:ln w=""6350"" cap=""flat"" cmpd=""sng"" algn=""ctr""><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:prstDash val=""solid""/><a:miter lim=""800000""/></a:ln><a:ln w=""12700"" cap=""flat"" cmpd=""sng"" algn=""ctr""><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:prstDash val=""solid""/><a:miter lim=""800000""/></a:ln><a:ln w=""19050"" cap=""flat"" cmpd=""sng"" algn=""ctr""><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:prstDash val=""solid""/><a:miter lim=""800000""/></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw blurRad=""57150"" dist=""19050"" dir=""5400000"" algn=""ctr"" rotWithShape=""0""><a:srgbClr val=""000000""><a:alpha val=""63000""/></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:solidFill><a:schemeClr val=""phClr""><a:tint val=""95000""/><a:satMod val=""170000""/></a:schemeClr></a:solidFill><a:gradFill rotWithShape=""1""><a:gsLst><a:gs pos=""0""><a:schemeClr val=""phClr""><a:tint val=""93000""/><a:satMod val=""150000""/><a:shade val=""98000""/><a:lumMod val=""102000""/></a:schemeClr></a:gs><a:gs pos=""50000""><a:schemeClr val=""phClr""><a:tint val=""98000""/><a:satMod val=""130000""/><a:shade val=""90000""/><a:lumMod val=""103000""/></a:schemeClr></a:gs><a:gs pos=""100000""><a:schemeClr val=""phClr""><a:shade val=""63000""/><a:satMod val=""120000""/></a:schemeClr></a:gs></a:gsLst><a:lin ang=""5400000"" scaled=""0""/></a:gradFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements><a:objectDefaults/><a:extraClrSchemeLst/><a:extLst><a:ext uri=""{05A4C25C-085E-4340-85A3-A5531E510DB2}""><thm15:themeFamily xmlns:thm15=""http://schemas.microsoft.com/office/thememl/2012/main"" name=""Office Theme"" id=""{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}"" vid=""{4A3C46E8-61CC-4603-A589-7422A47A8E4A}""/></a:ext></a:extLst></a:theme>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\worksheets\sheet1.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x14ac xr xr2 xr3"" xmlns:x14ac=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"" xmlns:xr=""http://schemas.microsoft.com/office/spreadsheetml/2014/revision"" xmlns:xr2=""http://schemas.microsoft.com/office/spreadsheetml/2015/revision2"" xmlns:xr3=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision3"" xr:uid=""{54E3D330-4E78-4755-89E0-1AADACAC4953}""><dimension ref=""A1:A3""/><sheetViews><sheetView tabSelected=""1"" workbookViewId=""0""><selection activeCell=""A4"" sqref=""A4""/></sheetView></sheetViews><sheetFormatPr defaultRowHeight=""15"" x14ac:dyDescent=""0.25""/><sheetData><row r=""1"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A1""><v>1</v></c></row><row r=""2"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A2""><v>2</v></c></row><row r=""3"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A3""><v>3</v></c></row></sheetData><pageMargins left=""0.7"" right=""0.7"" top=""0.75"" bottom=""0.75"" header=""0.3"" footer=""0.3""/></worksheet>";
            StartExstream(xContents, xFilename);

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();

            bool StartExstream(string strLine, string strFileName)
            {
                // Write the string to a file.
                using (StreamWriter outputFile = new StreamWriter(strFileName))
                {
                    outputFile.WriteLine(strLine);
                    return true;
                }
            }
        }
    }
}

最后壓縮包含 XML 的文件夾結構 -

namespace ZipFolder
// .NET Framework 4.7.2
// https://stackoverflow.com/questions/15241889/i-didnt-find-zipfile-class-in-the-system-io-compression-namespace?answertab=votes#tab-top
{
    class Program
    {
        static void Main(string[] args)
        {
            string xlPath = @"C:\Users\david\Desktop\Book3.xlsx";
            string folderPath = @"C:\Users\david\Desktop\Book3";

            System.IO.Compression.ZipFile.CreateFromDirectory(folderPath, xlPath);

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
}

這會生成一個名為 Book3.xlsx 的 Excel 文件,該文件有效並在 Windows 11 上的 Excel 365 中干凈地打開。

結果是一個非常簡單的 Excel 電子表格,但您可能需要對更復雜的版本進行逆向工程。 這是解壓縮 .xlsx 文件的代碼。

namespace UnZipXL
// .NET Framework 4.7.2
// https://stackoverflow.com/questions/15241889/i-didnt-find-zipfile-class-in-the-system-io-compression-namespace?answertab=votes#tab-top
{
    class Program
    {
        static void Main(string[] args)
        {
            string XLPath = @"C:\Users\david\Desktop\Book2.xlsx";
            string extractPath = @"C:\Users\david\Desktop\extract";

            System.IO.Compression.ZipFile.ExtractToDirectory(XLPath, extractPath);

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
}

我會建議使用 Openxml 庫,它是輕量級的,在處理 excel 時也減少了 ram 消耗,同時通過代碼操作它。

檢查一下不需要第三方庫,您可以使用它簡單地將數據表數據導出到excel文件

var dt = "your code for getting data into datatable";
            Response.ClearContent();
            Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd")));
            Response.ContentType = "application/vnd.ms-excel";
            string tab = "";
            foreach (DataColumn dataColumn in dt.Columns)
            {
                Response.Write(tab + dataColumn.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");
            int i;
            foreach (DataRow dataRow in dt.Rows)
            {
                tab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    Response.Write(tab + dataRow[i].ToString());
                    tab = "\t";
                }
                Response.Write("\n");
            }
            Response.End();

我正在使用以下代碼創建 excel 2007 文件,該文件創建文件並寫入該文件,但是當我打開文件但它給我錯誤,exel 無法打開文件 bcz 文件可能已損壞或文件的擴展名不兼容。 但如果我使用 .xls 作為文件,它可以正常工作

for (int i = 0; i < TotalFile; i++)
{
    Contact.Clear();
    if (innerloop == SplitSize)
    {
        for (int j = 0; j < SplitSize; j++)
        {
            string strContact = DSt.Tables[0].Rows[i * SplitSize + j][0].ToString();
            Contact.Add(strContact);
        }
        string strExcel = strFileName + "_" + i.ToString() + ".xlsx";
                         File.WriteAllLines(strExcel, Contact.ToArray());
    }
}

也參考鏈接

http://dotnet-magic.blogspot.in/2011/10/createformat-excel-file-from-cnet.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM