用C# 编写一个导出mysql 数据库word文档的完整代码要求导出的文档美观可阅读性好
以下是一个使用C#编写的导出MySQL数据库为Word文档的示例代码:
using System;
using System.Data;
using System.IO;
using MySql.Data.MySqlClient;
using Spire.Doc;
using Spire.Doc.Documents;
public class Program
{
public static void Main(string[] args)
{
string connectionString = "server=localhost;port=3306;database=mydatabase;uid=root;pwd=123456;";
string query = "SELECT * FROM mytable;";
// 创建MySQL连接
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
// 执行查询
MySqlCommand command = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
// 创建Word文档
Document document = new Document();
Section section = document.AddSection();
// 添加表格
Table table = section.AddTable();
table.ResetCells(dataTable.Rows.Count + 1, dataTable.Columns.Count);
// 添加表头
for (int i = 0; i < dataTable.Columns.Count; i++)
{
table.Rows[0].Cells[i].AddParagraph().AppendText(dataTable.Columns[i].ColumnName);
}
// 添加表格数据
for (int i = 0; i < dataTable.Rows.Count; i++)
{
for (int j = 0; j < dataTable.Columns.Count; j++)
{
table.Rows[i + 1].Cells[j].AddParagraph().AppendText(dataTable.Rows[i][j].ToString());
}
}
// 保存为Word文档
string outputPath = "output.docx";
document.SaveToFile(outputPath, FileFormat.Docx);
document.Close();
Console.WriteLine("导出成功!保存路径:" + outputPath);
}
}
}
在使用此代码之前,请确保你已经安装了Spire.Doc库。你可以使用NuGet来安装Spire.Doc:
- 在Visual Studio中打开“工具”菜单。
- 选择“NuGet包管理器”。
- 选择“程序包管理器控制台”。
- 在控制台中输入以下命令并按回车键安装Spire.Doc:
Install-Package Spire.Doc
在代码中,你需要将connectionString替换为你的MySQL连接字符串。query变量可以根据你的需求自定义查询语句。
代码将查询结果导出为Word文档,其中表头为MySQL表的列名,表格数据为MySQL表中的记录。导出的Word文档将保存在项目的根目录下,文件名为output.docx。你可以根据需要修改保存路径和文件名。
此代码使用了Spire.Doc库来创建和保存Word文档,它提供了丰富的API来创建和编辑Word文档,可以自定义文档的格式和样式,以满足你的美观和可阅读性的要求
原文地址: http://www.cveoy.top/t/topic/iZWh 著作权归作者所有。请勿转载和采集!