将数据库所有表导出至一个excel文件中,存在多个sheet页,每个sheet页的名字就是数据库的表名
/// <summary>
/// 导出所有表
/// </summary>
/// <param name="tableNames">存储所有表名的集合</param>
/// <param name="helper">操作数据库对象</param>
/// <param name="txtPath">文件路径</param>
/// <exception cref="Exception"></exception>
public static void ExportAllTable(List<string> tableNames, SqlHelper helper, string txtPath)
{
try
{
// 创建新的Excel文件
var workbook = new HSSFWorkbook();
foreach (string tableName in tableNames)
{
// 查询表结构与数据
DataTable dataTable = ExecuteSelectAll(tableName, helper);
// 创建新的工作表
ISheet sheet = workbook.CreateSheet(tableName);
// 写入表头
IRow headerRow = sheet.CreateRow(0);
for (int i = 0; i < dataTable.Columns.Count; i++)
{
headerRow.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);
}
// 写入数据行
for (int r = 0; r < dataTable.Rows.Count; r++)
{
IRow dataRow = sheet.CreateRow(r + 1);
for (int c = 0; c < dataTable.Columns.Count; c++)
{
dataRow.CreateCell(c).SetCellValue(dataTable.Rows[r][c].ToString());
}
}
}
// 保存Excel文件
using FileStream fs = File.OpenWrite(txtPath);
workbook.Write(fs);
MessageBox.Show("导出成功");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 执行全表查询的方法
/// </summary>
/// <param name="tableName"></param>
/// <param name="helper"></param>
/// <returns></returns>
private static DataTable ExecuteSelectAll(string tableName, SqlHelper helper)
{
string sql = $"SELECT * FROM {tableName}";
DataTable dataTable = helper.ExecuteDataTable(sql);
return dataTable;
}