- [C#] Hướng dẫn convert HTML code sang PDF File trên NetCore 7 Winform
- [C#] Hướng dẫn viết ứng dụng chat với Gemini AI Google Winform
- Hướng dẫn khóa file bằng nhiều process id, không cho xóa tập tin
- Hướng dẫn cách tạo Product Id cho ứng dụng phần mềm XXXXX-XXXXX-XXXXX-XXXXX
- [SQLSERVER] Hướng dẫn tạo script sql từ ứng dụng Sqlserver management Studio
- [C#] Hướng dẫn sử dụng thư viện AutoITx lấy id và password Ultraviewer trên winform
- [VB.NET] Hướng dẫn lấy thông tin tài khoản đăng nhập windows và khởi động lại ứng dụng ở chế độ Administrator
- [C#] Sử dụng thư viện Polly gửi lại request api khi request bị lỗi hay rớt mạng
- [DEVEXPRESS] Chia sẻ source code tạo báo cáo report in tem nhãn label trên C# winform
- [DEVEXPRESS] Hướng dẫn vẽ biểu đồ Bar Chart trên Winform
- [C#] Tạo form đăng nhập và đăng ký với hiệu ứng Sliding Animation Effect
- [C#] Hướng dẫn tạo thanh toán đơn hàng qua mã vạch VietQR sử dụng API PayOS hoàn toàn miễn phí
- [C#] Hướng dẫn ghi log ra RichTextBox giống Console trên Winform sử dụng thư viện Serilog
- [C#] Hướng dẫn cách tạo mã QR Code trên file Excel
- [VB.NET] Gởi tin nhắn và file đính kèm qua ứng dụng gởi tin nhắn Whats App
- [C#] Viết ứng dụng Auto Fill list Textbox from clipboard Winform
- [TOOL] Chia sẻ phần mềm thay đổi thông tin cấu hình máy tính
- [C#] Hướng dẫn Export dữ liệu ra file Microsoft Word Template
- [C#] Chia sẻ source code tool kiểm tra domain website
- [C#] Hướng dẫn tạo file PDF sử dụng thư viện QuestPDF
[C#] Export tất cả các bảng table trong sqlserver thành từng file Excel
Xin chào các bạn, bài viết hôm nay mình sẽ chia sẻ đến các bạn cách xuất tất cả các bảng dữ liệu trong cơ sở dữ liệu Sqlserver ra file Excel.
[C#] Export all table sqlserver to Excel File
Trong lập trình ứng dụng, đôi lúc các bạn muốn xuất tất cả các bảng của Table ra file Excel dùng để import vào cơ sở dữ liệu khác như: Mysql, sqlite...
Thì bài viết dưới đây sẽ giúp export một cách dễ dàng.
Để thực hiện chúng ta thực hiện hai connection.
- Connection kết nối SQL Server
- Connection kết nối Excel File sử dụng Oledb
Khi các bạn chạy mà nếu có báo lỗi:
Microsoft.ACE.OLEDB.12.0 provider is not registered on the local machine
Thì bạn download Office System Driver: Data Connectivity Components, về để cài đặt vào nhé.
Kết quả khi chạy ứng dụng chương trình:
Source code Export Excel From Sqlserver C#:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExportAllExcel
{
class Program
{
static void Main(string[] args)
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
string FolderPath = @"E:\Destination\";
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "Data Source = (local); Initial Catalog =TMV_OLIVER; "
+ "Integrated Security=true;";
string query = "SELECT Schema_name(schema_id) AS SchemaName,name AS TableName";
query += " FROM sys.tables WHERE is_ms_shipped = 0";
SqlCommand cmd = new SqlCommand(query, SQLConnection);
SQLConnection.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
SQLConnection.Close();
foreach (DataRow dt_row in dt.Rows)
{
string SchemaName = "";
string TableName = "";
object[] array = dt_row.ItemArray;
SchemaName = array[0].ToString();
TableName = array[1].ToString();
string ExcelFileName = "";
// ExcelFileName = SchemaName + "_" + TableName + "_" + datetime;
ExcelFileName = TableName ;
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source="
+ FolderPath + ExcelFileName
+ ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
string queryString =
"SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, SQLConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
string TableColumns = "";
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table [" + SchemaName + "_" +
TableName + "] (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
foreach (DataTable table in ds.Tables)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into [" + SchemaName + "_" + TableName
+ "] (" + sqlCommandValue + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
Excel_OLE_Con.Close();
Console.WriteLine($"Export Excel: {TableName} Finish!");
}
Console.ReadLine();
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
Console.ReadLine();
}
}
}
}
Thanks for watching!