C# 操作 Excel 不保存关闭代码示例
以下是使用 C# 代码操作 Excel 并关闭工作簿而不保存更改的示例:\n\ncsharp\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Excel = Microsoft.Office.Interop.Excel;\n\nnamespace ExcelOperation\n{\n class Program\n {\n static void Main(string[] args)\n {\n // 创建 Excel 对象\n Excel.Application excel = new Excel.Application();\n excel.Visible = true;\n\n // 打开已存在的工作簿\n Excel.Workbook workbook = excel.Workbooks.Open("C:\\path\\to\\your\\file.xlsx");\n\n // 选择第一个工作表\n Excel.Worksheet worksheet = workbook.Sheets[1];\n\n // 操作 Excel 内容\n // ...\n\n // 关闭工作簿但不保存更改\n workbook.Close(false);\n\n // 退出 Excel 应用程序\n excel.Quit();\n\n // 释放 Excel 对象\n System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);\n System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);\n System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);\n\n worksheet = null;\n workbook = null;\n excel = null;\n\n GC.Collect();\n }\n }\n}\n\n\n请注意,上述代码使用了 Microsoft.Office.Interop.Excel 库来操作 Excel,因此需要在项目中引用此库。此外,如果你的 Excel 文件格式不是 .xlsx,请根据实际情况修改文件路径。
原文地址: https://www.cveoy.top/t/topic/pYuH 著作权归作者所有。请勿转载和采集!