
word
csharpusing System;using System.IO;using Microsoft.Office.Interop.excel;using Microsoft.Office.Interop.word;class Program { static void MAIn(string[] args) { // 创建excel应用程序对象 Application excelApp = new Application(); // 创建工作簿对象 Workbook workbook = excelApp.Workbooks.Open("C:\data.xlsx"); // 获取第一个工作表对象 Worksheet worksheet = workbook.Sheets[1]; // 获取数据源 string[] data = { "Name", "Age", "Gender" }; // 创建文件对象 File file = new File("C:\output.docx"); // 获取输出流 TextStream output = new TextStream(file, "Text"); // 将数据写入到输出流中 for (int i = 0; i < data.Length; i++) { for (int j = 0; j < data[i].Length; j++) { output.Write(data[i][j] + " "); } output.WriteLine(); } // 关闭输出流,并关闭文件 output.Close(); file.Close(); // 关闭excel应用程序对象 excelApp.Quit(); }}以上代码会将数据源中的姓名、年龄和性别三个字段的内容按照每行写入到指定的word文档中。类似于地,以下是一个将数字数据导入到excel文档的示例代码片段:csharpusing System;using System.IO;using Microsoft.Office.Interop.excel;using Microsoft.Office.Interop.word;class Program { static void MAIn(string[] args) { // 创建excel应用程序对象 Application excelApp = new Application(); // 创建工作簿对象 Workbook workbook = excelApp.Workbooks.Open("C:\data.xlsx"); // 获取第一个工作表对象 Worksheet worksheet = workbook.Sheets[1]; // 获取数据源 string[] data = { "Name", "Age", "Gender" }; // 创建文件对象 File file = new File("C:\output.xlsx"); // 获取输出流 SheetStream output = new SheetStream(file, "Sheet1"); // 将数据写入到输出流中 for (int i = 0; i < data.Length; i++) { for (int j = 0; j < data[i].Length; j++) { output.Write(data[i][j] + " "); } output.WriteLine(); } // 关闭输出流,并关闭文件 output.Close(); file.Close(); // 关闭excel应用程序对象 excelApp.Quit();}Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号