c# 将xml格式的Excel文件转换为标准的Excel

12 篇文章 0 订阅

http://hi.baidu.com/sbiweeq/item/c0b597be2ac3c6f363388ebf

public static void ConvertExcel(string savePath)
     {
         //将xml文件转换为标准的Excel格式
         Object Nothing = Missing.Value;//由于yongCOM组件很多值需要用Missing.Value代替   
         Excel.Application ExclApp = new Excel.ApplicationClass();// 初始化
         Excel.Workbook ExclDoc = ExclApp.Workbooks.Open(savePath, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing);//打开Excl工作薄   
         try
         {
             Object format = Excel.XlFileFormat.xlWorkbookNormal;//获取Excl 2007文件格式   
             ExclApp.DisplayAlerts = false;
             ExclDoc.SaveAs(savePath, format, Nothing, Nothing, Nothing, Nothing, Excel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing);//保存为Excl 2007格式   
         }
         catch (Exception ex) { }
         ExclDoc.Close(Nothing, Nothing, Nothing);
         ExclApp.Quit();
     }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 中,你可以使用 `Microsoft.Office.Interop.Excel` 程序集中的 `Workbook` 和 `Worksheet` 类来读取 Excel 文件中的数据,然后将其转换XML 格式并保存为文件。 以下是一个简单的示例代码,演示如何将 Excel 文件转换XML 文件: ```csharp using System.Xml; using Microsoft.Office.Interop.Excel; // 创建一个新的Excel应用程序实例 Application excel = new Application(); Workbook workbook = excel.Workbooks.Open(@"C:\path\to\workbook.xlsx"); Worksheet sheet = workbook.Sheets[1]; // 创建一个新的XmlDocument对象 XmlDocument xmlDocument = new XmlDocument(); // 创建根元素 XmlElement rootElement = xmlDocument.CreateElement("Workbook"); xmlDocument.AppendChild(rootElement); // 逐行读取Excel数据并将其转换Xml元素 for (int i = 1; i <= sheet.UsedRange.Rows.Count; i++) { XmlElement rowElement = xmlDocument.CreateElement("Row"); rootElement.AppendChild(rowElement); for (int j = 1; j <= sheet.UsedRange.Columns.Count; j++) { object cellValue = sheet.Cells[i, j].Value2; XmlElement cellElement = xmlDocument.CreateElement("Cell"); cellElement.InnerText = cellValue.ToString(); rowElement.AppendChild(cellElement); } } // 保存Xml文件 xmlDocument.Save(@"C:\path\to\output.xml"); // 关闭Excel应用程序和工作簿 workbook.Close(false); excel.Quit(); ``` 在上面的示例代码中,我们首先使用 `Microsoft.Office.Interop.Excel` 程序集创建了一个新的 Excel 应用程序实例,并打开了一个工作簿。然后,我们选择了工作簿中的第一个工作表,并使用 `UsedRange` 属性获取其使用的范围。 接下来,我们创建了一个新的 `XmlDocument` 对象,并为其添加了一个根元素。然后,我们使用一个循环逐行读取 Excel 文件中的数据,并将其转换XML 元素。最后,我们保存了 XML 文件,并关闭了 Excel 应用程序和工作簿。 请注意,上述示例使用了 `Value2` 属性来获取单元格的值。这是因为 `Value2` 属性返回一个未经格式化的值,可以更快地读取和处理数据。如果需要,你也可以使用 `Value` 属性来获取单元格的格式化值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值