- [C#] Viết ứng dụng xem và dò kết quả xổ số kiến thiết miền nam
- [EBOOK] Chia sẽ giáo trình học lập trình C - Giáo sư Phạm Văn Ất
- [C#] Hướng dẫn viết ứng dụng theo dõi máy in bao nhiêu trang (Monitor Printer)
- [C#] Lấy thông tin cấu hình máy tính xuất ra text file winform
- [C#] Chia sẽ class Install, Uninstall, Start và Stop Services Winform
- [C#] Tìm kiếm tập tin file nhanh chóng trên Winform sử dụng thư viện FastSearchLibrary
- [C#] Giới thiệu thư viện Fluent FTP Awesome dùng để làm việc với FTP
- [C#] Sử dụng thư viện Mini Profiler Integrations ghi log thực hiện các câu lệnh SQL
- [DEVEXPRESS] Thiết kế Dropdown ButtonBarItem trên Form Ribbon
- [C#] Lưu trạng thái các control trên Winform vào Registry Windows
- [C#] Ứng dụng ví dụ Simple Observer Pattern tăng giảm số lượng trên winform
- [C#] Hướng dẫn lấy thời gian thực server time trên winform
- [DEVEXPRESS] Hướng dẫn bật tính năng Scroll Pixcel in Touch trên GridView
- [DEVEXPRESS] Hướng dẫn sử dụng TileBar viết ứng dụng duyệt hình ảnh Winform
- [DEVEXPRESS] Tô màu border TextEdit trên Winform
- [C#] Lấy dữ liệu từ Console Write hiển thị lên textbox Winform
- [C#] Hiển thị Progress bar trên Window Console
- [C#] Di chuyển control Runtime và lưu layout trên winform
- [SQLSERVER] Sử dụng hàm NULL IF
- [C#] Chia sẽ source code mã đi tuần bằng giao diện Winform
[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!