Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Data.SqlClient;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using System.Xml;
- using System.Threading;
- namespace ExcelExpImp
- {
- public partial class Form1 : Form
- {
- //Variaveis globais
- string servidor;
- string db;
- string username;
- string password;
- string connectionString;
- bool IsConnected = false;
- int n;
- XmlNode dbNode;
- //Inicializacão de Controlos
- DataGridView dgvTables = new DataGridView();
- ListBox lbExport = new ListBox();
- Label lblExpTitle = new Label();
- Label lblImpTitle = new Label();
- Button btnImport = new Button();
- Button btnDelete = new Button();
- Button btnAdd = new Button();
- Button btnExport = new Button();
- Button btnUpdate = new Button();
- Button btnExportData = new Button();
- public Form1()
- {
- InitializeComponent();
- }
- private void btnClose_Click(object sender, EventArgs e)
- {
- this.Close();
- }
- private void btnMinimize_Click(object sender, EventArgs e)
- {
- this.WindowState = FormWindowState.Minimized;
- }
- public void SplashStart()
- {
- Application.Run(new Splashcs());
- }
- private void btnConnect_Click(object sender, EventArgs e)
- {
- Thread t = new Thread(new ThreadStart(SplashStart));
- t.Start();
- Thread.Sleep(3000);
- servidor = txtServer.Text;
- db = txtDb.Text;
- username = txtUser.Text;
- password = txtPass.Text;
- File.Delete("conf.xml");
- XmlDocument xmlDoc = new XmlDocument();
- XmlNode rootNode = xmlDoc.CreateElement("Configuracao");
- xmlDoc.AppendChild(rootNode);
- XmlAttribute servAtt = xmlDoc.CreateAttribute("Servidor");
- servAtt.Value = servidor;
- XmlAttribute dbAtt = xmlDoc.CreateAttribute("Base_De_Dados");
- dbAtt.Value = db;
- XmlAttribute userAtt = xmlDoc.CreateAttribute("Utilizador");
- userAtt.Value = username;
- XmlAttribute passAtt = xmlDoc.CreateAttribute("palavra-passe");
- passAtt.Value = password;
- rootNode.Attributes.Append(servAtt);
- rootNode.Attributes.Append(dbAtt);
- rootNode.Attributes.Append(userAtt);
- rootNode.Attributes.Append(passAtt);
- xmlDoc.Save("conf.xml");
- IsConnected = true;
- t.Abort();
- MessageBox.Show("Conectado com sucesso");
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- InitialVisibleControls();
- LoadConf();
- CreateControls();
- }
- private void GetTables()
- {
- SetConnectionString();
- SqlConnection cnn = new SqlConnection(connectionString);
- cnn.Open();
- List<string> result = new List<string>();
- SqlCommand cmd = new SqlCommand("SELECT name FROM sys.Tables", cnn);
- SqlDataReader reader = cmd.ExecuteReader();
- while (reader.Read())
- result.Add(reader["name"].ToString());
- dgvTables.Rows.Clear();
- n = 0;
- foreach (string tableName in result)
- {
- n++;
- dgvTables.Rows.Add(n, tableName);
- }
- cnn.Close();
- }
- private void InitialVisibleControls()
- {
- dgvTables.Visible = false;
- lbExport.Visible = false;
- btnDelete.Visible = false;
- btnAdd.Visible = false;
- btnExport.Visible = false;
- lblExpTitle.Visible = false;
- btnImport.Visible = false;
- lblImpTitle.Visible = false;
- btnExportData.Visible = false;
- btnUpdate.Visible = false;
- }
- private void CreateControls()
- {
- //propriedades dgvTables
- dgvTables.Columns.Add("numTable","Nr. Tabela");
- dgvTables.Columns.Add("name","Nome da Tabela");
- dgvTables.Columns[0].Width = 35;
- dgvTables.Columns[1].Width = 397;
- dgvTables.Location = new Point(175,64);
- dgvTables.Size = new Size(475,280);
- //Propriedade lbExport
- lbExport.Text = "";
- lbExport.Location = new Point(660,65);
- lbExport.Size = new Size(175,230);
- //Propriedades btnDelete
- btnDelete.Text = "Eliminar";
- btnDelete.FlatAppearance.BorderSize = 0;
- btnDelete.FlatStyle = FlatStyle.Flat;
- btnDelete.Location = new Point(660, 300);
- btnDelete.Size = new Size(175,40);
- btnDelete.BackColor = Color.FromArgb(5, 172, 201);
- btnDelete.Font = new Font("Verdana",12);
- btnDelete.ForeColor = Color.White;
- btnDelete.Click += BtnDelete_Click;
- //Propriedades btnAdd
- btnAdd.Text = "Adicionar";
- btnAdd.FlatAppearance.BorderSize = 0;
- btnAdd.FlatStyle = FlatStyle.Flat;
- btnAdd.Location = new Point(474, 345);
- btnAdd.Size = new Size(175, 40);
- btnAdd.BackColor = Color.FromArgb(5, 172, 201);
- btnAdd.Font = new Font("Verdana", 12);
- btnAdd.ForeColor = Color.White;
- btnAdd.Click += BtnAdd_Click;
- //Propriedades btnExport
- btnExport.Text = "Exportar Template";
- btnExport.FlatAppearance.BorderSize = 0;
- btnExport.FlatStyle = FlatStyle.Flat;
- btnExport.Location = new Point(660, 345);
- btnExport.Size = new Size(175, 40);
- btnExport.BackColor = Color.FromArgb(5, 172, 201);
- btnExport.Font = new Font("Verdana", 12);
- btnExport.ForeColor = Color.White;
- btnExport.Click += BtnExport_Click;
- //Propriedades btnExportData
- btnExportData.Text = "Exportar Dados";
- btnExportData.FlatAppearance.BorderSize = 0;
- btnExportData.FlatStyle = FlatStyle.Flat;
- btnExportData.Location = new Point(290, 345);
- btnExportData.Size = new Size(175, 40);
- btnExportData.BackColor = Color.FromArgb(5, 172, 201);
- btnExportData.Font = new Font("Verdana", 12);
- btnExportData.ForeColor = Color.White;
- btnExportData.Click += BtnExportData_Click;
- //Propriedade lblExpTitle
- lblExpTitle.Text = "Exportar";
- lblExpTitle.Font = new Font("Verdana", 18);
- lblExpTitle.Location = new Point(440,15);
- lblExpTitle.Size = new Size(200, 40);
- lblExpTitle.ForeColor = Color.White;
- //Propriedade lblImpTitle
- lblImpTitle.Text = "Importar";
- lblImpTitle.Font = new Font("Verdana", 18);
- lblImpTitle.Location = new Point(440, 15);
- lblImpTitle.Size = new Size(200, 40);
- lblImpTitle.ForeColor = Color.White;
- //Propriedades btnImport
- btnImport.Text = "Importar";
- btnImport.FlatAppearance.BorderSize = 0;
- btnImport.FlatStyle = FlatStyle.Flat;
- btnImport.Location = new Point(420, 180);
- btnImport.Size = new Size(175, 40);
- btnImport.BackColor = Color.FromArgb(5, 172, 201);
- btnImport.Font = new Font("Verdana", 12);
- btnImport.ForeColor = Color.White;
- btnImport.Click += BtnImport_Click;
- //Propriedades btnUpdate
- btnUpdate.Text = "Update";
- btnUpdate.FlatAppearance.BorderSize = 0;
- btnUpdate.FlatStyle = FlatStyle.Flat;
- btnUpdate.Location = new Point(176, 345);
- btnUpdate.Size = new Size(105, 40);
- btnUpdate.BackColor = Color.FromArgb(5, 172, 201);
- btnUpdate.Font = new Font("Verdana", 12);
- btnUpdate.ForeColor = Color.White;
- btnUpdate.Click += BtnUpdate_Click;
- //adicionar os controlos ao painel
- panelMiddle.Controls.Add(btnUpdate);
- panelMiddle.Controls.Add(btnExportData);
- panelMiddle.Controls.Add(btnImport);
- panelMiddle.Controls.Add(lblImpTitle);
- panelMiddle.Controls.Add(lblExpTitle);
- panelMiddle.Controls.Add(btnExport);
- panelMiddle.Controls.Add(btnAdd);
- panelMiddle.Controls.Add(btnDelete);
- panelMiddle.Controls.Add(lbExport);
- panelMiddle.Controls.Add(dgvTables);
- }
- private void BtnUpdate_Click(object sender, EventArgs e)
- {
- OFD.ShowDialog();
- string path = OFD.FileName;
- bool verif = false;
- Thread t = new Thread(new ThreadStart(SplashStart));
- t.Start();
- Thread.Sleep(500);
- LoadConf();
- SetConnectionString();
- Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
- Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(path);
- SqlConnection cnn = new SqlConnection(connectionString);
- cnn.Open();
- foreach (Microsoft.Office.Interop.Excel.Worksheet ws in wb.Worksheets)
- {
- string tablename = ws.Cells[1, 1].Value.ToString();
- SqlCommand sqlPrimaryKey = new SqlCommand("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1 AND TABLE_NAME = '" + tablename + "'",cnn);
- string primaryKey = sqlPrimaryKey.ExecuteScalar().ToString();
- Microsoft.Office.Interop.Excel.Range aRange = ws.UsedRange;
- List<string> headers = new List<string>();
- string[,] data = new string[1000, 1000];
- int count = 0;
- int indexPrimaryKey = 0;
- for (int i = 0; i < ws.UsedRange.Columns.Count; i++)
- {
- headers.Add(ws.Cells[2, i + 1].Value.ToString());
- if (ws.Cells[2, i + 1].Value.ToString() == primaryKey)
- {
- indexPrimaryKey = i;
- }
- count++;
- }
- for (int i = 0; i < count; i++)
- {
- for (int j = 1; j <= aRange.Rows.Count - 2; j++)
- {
- SqlCommand sqlGetDataType = new SqlCommand("select DATA_TYPE from INFORMATION_SCHEMA.COLUMNS IC where TABLE_NAME = '" + tablename + "' and COLUMN_NAME = '" + ws.Cells[2, i + 1].Value.ToString() + "'", cnn);
- string DataType = sqlGetDataType.ExecuteScalar().ToString();
- if (ws.Cells[j + 2, i + 1].Value != null)
- {
- data[j - 1, i] = ws.Cells[j + 2, i + 1].Value.ToString();
- }
- else
- {
- if (DataType == "int" || DataType == "tinyint" || DataType == "decimal" || DataType == "numeric")
- {
- data[j - 1, i] = "0";
- }
- else if (DataType == "nvarchar" || DataType == "varchar")
- {
- data[j - 1, i] = " ";
- }
- else if (DataType == "date")
- {
- data[j - 1, i] = "01/01/1222";
- }
- else if (DataType == "datetime")
- {
- data[j - 1, i] = "2001-01-01 00:00:00.000";
- }
- else if (DataType == "uniqueidentifier")
- {
- data[j - 1, i] = "00000000-0000-0000-0000-000000000000";
- }
- else
- {
- data[j - 1, i] = "0";
- }
- }
- }
- }
- DataTable dt = new DataTable();
- SqlDataAdapter sda = new SqlDataAdapter("select [" + primaryKey + "] FROM [" + tablename + "]",cnn);
- sda.Fill(dt);
- int rows = dt.Rows.Count;
- for (int i = 1; i <= aRange.Rows.Count - 2; i++)
- {
- for (int y = 0; y < rows; y++)
- {
- try
- {
- if (data[i - 1, indexPrimaryKey] == dt.Rows[y].Field<Int32>(0).ToString())
- {
- string updateCommand = "Update " + tablename + " Set ";
- for (int j = 0; j < count; j++)
- {
- updateCommand += headers[j] + "='" + data[i - 1, j] + "',";
- }
- updateCommand = updateCommand.Remove(updateCommand.Length - 1);
- updateCommand += " where " + headers[indexPrimaryKey] + "='" + data[i - 1, indexPrimaryKey] + "'";
- SqlCommand sqlUpdate = new SqlCommand(updateCommand, cnn);
- sqlUpdate.ExecuteNonQuery();
- }
- }
- catch (Exception)
- {
- if (data[i - 1, indexPrimaryKey] == dt.Rows[y].Field<string>(0).ToString())
- {
- string updateCommand = "Update " + tablename + " Set ";
- for (int j = 0; j < count; j++)
- {
- updateCommand += headers[j] + "='" + data[i - 1, j] + "',";
- }
- updateCommand = updateCommand.Remove(updateCommand.Length - 1);
- updateCommand += " where " + headers[indexPrimaryKey] + "='" + data[i - 1, indexPrimaryKey] + "'";
- SqlCommand sqlUpdate = new SqlCommand(updateCommand, cnn);
- sqlUpdate.ExecuteNonQuery();
- }
- }
- }
- }
- }
- t.Abort();
- app.Quit();
- cnn.Close();
- if (verif == false)
- {
- MessageBox.Show("Update com sucesso");
- }
- else
- {
- MessageBox.Show("Update sem sucesso");
- }
- }
- private void BtnExportData_Click(object sender, EventArgs e)
- {
- if (lbExport.Items.Count != 0)
- {
- Thread t = new Thread(new ThreadStart(SplashStart));
- t.Start();
- Thread.Sleep(8000);
- int count = 0;
- int repeatedNames = 0;
- List<String> nomeTabela = new List<string>();
- foreach (string nome in lbExport.Items)
- {
- nomeTabela.Add(nome);
- }
- Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application
- {
- Visible = false
- };
- SqlConnection cnn = new SqlConnection(connectionString);
- Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
- object MissingValue = System.Reflection.Missing.Value;
- foreach (string tableName in nomeTabela)
- {
- string excelName = null;
- int numCar = 0;
- List<string> headers = new List<string>();
- SqlDataAdapter sda = new SqlDataAdapter("Select * FROM [" + tableName + "]", cnn);
- DataTable dt = new DataTable();
- dt.Clear();
- sda.Fill(dt);
- Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet;
- if (count != lbExport.Items.Count - 1)
- {
- wb.Worksheets.Add(ws);
- }
- ws.Cells[1][1] = tableName;
- int countNumVezes = 0;
- for (int i = 0; i < dt.Columns.Count; i++)
- {
- cnn.Open();
- SqlCommand sqlcom = new SqlCommand("select is_identity from sys.columns where OBJECT_ID = OBJECT_ID('" + tableName + "') and name = '" + dt.Columns[i].ColumnName + "';", cnn);
- object isIncremental = sqlcom.ExecuteScalar();
- if (!(Convert.ToBoolean(isIncremental)) && (dt.Columns[i].ColumnName != "timestamp"))
- {
- ws.Cells[2, i + 1 - countNumVezes] = dt.Columns[i].ColumnName;
- headers.Add(dt.Columns[i].ColumnName);
- }
- else
- {
- countNumVezes++;
- }
- cnn.Close();
- }
- countNumVezes = 0;
- for (int i = 1; i <= dt.Rows.Count; i++)
- {
- countNumVezes = 0;
- for (int j = 1; j <= dt.Columns.Count; j++)
- {
- cnn.Open();
- SqlCommand sqlcom = new SqlCommand("select is_identity from sys.columns where OBJECT_ID = OBJECT_ID('" + tableName + "') and name = '" + dt.Columns[j-1].ColumnName + "';", cnn);
- object isIncremental = sqlcom.ExecuteScalar();
- SqlCommand sqlGetDataType = new SqlCommand("select DATA_TYPE from INFORMATION_SCHEMA.COLUMNS IC where TABLE_NAME = '" + tableName + "' and COLUMN_NAME = '" + dt.Columns[j-1].ColumnName + "'", cnn);
- string DataType = sqlGetDataType.ExecuteScalar().ToString();
- if (!(Convert.ToBoolean(isIncremental)) && (dt.Columns[j-1].ColumnName != "timestamp"))
- {
- if (DataType != "timestamp")
- {
- if (DataType == "date" || DataType == "datetime")
- {
- ws.Cells[i + 2, j - countNumVezes] = dt.Rows[i - 1].Field<DateTime>(j - 1);
- }
- else if (DataType == "int" || DataType == "tinyint")
- {
- ws.Cells[i + 2, j - countNumVezes] = dt.Rows[i - 1].Field<Int32>(j - 1);
- }
- else if(DataType == "decimal" || DataType == "float" || DataType == "double")
- {
- ws.Cells[i + 2, j - countNumVezes] = dt.Rows[i - 1].Field<decimal>(j - 1);
- }
- else if (DataType == "uniqueidentifier")
- {
- }
- else if(DataType == "nvarchar")
- {
- ws.Cells[i + 2, j - countNumVezes] = dt.Rows[i - 1].Field<string>(j - 1);
- }
- else if(DataType == "datetime" || DataType == "smalldatetime" || DataType == "date")
- {
- ws.Cells[i + 2, j - countNumVezes] = dt.Rows[i - 1].Field<DateTime>(j - 1);
- }
- else
- {
- ws.Cells[i + 2, j - countNumVezes] = dt.Rows[i - 1].Field<string>(j - 1);
- }
- }
- }
- else
- {
- countNumVezes++;
- }
- cnn.Close();
- }
- }
- ws.Columns.AutoFit();
- if (tableName.ToLower().Contains("history") == true)
- {
- tableName.Replace("history", "xxxxxxx");
- }
- foreach (char letra in tableName.ToCharArray())
- {
- if (letra == '\\' || letra == '/' || letra == '?' || letra == '*')
- {
- excelName += "_";
- }
- else if (numCar == 30)
- {
- goto KeepGoing;
- }
- else
- {
- excelName += letra;
- }
- numCar++;
- }
- KeepGoing:
- try
- {
- //atribuição de um nome á worksheet
- ws.Name = excelName;
- }//Se o nome já foi atribuido ele acrescenta-lhe um numero
- catch (System.Runtime.InteropServices.COMException)
- {
- int tamanho = excelName.Length;
- ws.Name = excelName.Insert(tamanho, repeatedNames.ToString());
- repeatedNames++;
- }
- if (count == 0)
- {
- //abre o dialogo e guarda o excel no caminho indicado
- SFD.ShowDialog();
- wb.SaveAs(SFD.FileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, MissingValue, MissingValue, MissingValue, MissingValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, MissingValue, MissingValue, MissingValue, MissingValue, MissingValue);
- }
- //Conta o nº de tabelas
- count++;
- }
- //fechar a coneccão com a base de dados
- cnn.Close();
- //fecha o workbook
- wb.Close(true, MissingValue, MissingValue);
- //fecha a aplicação excel
- app.Quit();
- //Guarda no excel as ulltimas tabelas exportadas
- SaveToXML(nomeTabela);
- t.Abort();
- MessageBox.Show("Exportado com Sucesso");
- }
- else
- {
- MessageBox.Show("Não tem tabelas para exportar");
- }
- }
- private void BtnImport_Click(object sender, EventArgs e)
- {
- OFD.ShowDialog();
- string path = OFD.FileName;
- bool verif = false;
- Thread t = new Thread(new ThreadStart(SplashStart));
- t.Start();
- Thread.Sleep(500);
- LoadConf();
- SetConnectionString();
- Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
- Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(path);
- SqlConnection cnn = new SqlConnection(connectionString);
- cnn.Open();
- foreach (Microsoft.Office.Interop.Excel.Worksheet ws in wb.Worksheets)
- {
- string tablename = ws.Cells[1, 1].Value.ToString();
- Microsoft.Office.Interop.Excel.Range aRange = ws.UsedRange;
- List<string> headers = new List<string>();
- string[,] data = new string[10000, 10000];
- int count = 0;
- for (int i = 0; i < ws.UsedRange.Columns.Count; i++)
- {
- headers.Add(ws.Cells[2, i + 1].Value.ToString());
- count++;
- }
- for (int i = 0; i < count; i++)
- {
- for (int j = 1; j <= aRange.Rows.Count - 1; j++)
- {
- SqlCommand sqlGetDataType = new SqlCommand("select DATA_TYPE from INFORMATION_SCHEMA.COLUMNS IC where TABLE_NAME = '" + tablename + "' and COLUMN_NAME = '" + ws.Cells[2, i + 1].Value.ToString() + "'", cnn);
- string DataType = sqlGetDataType.ExecuteScalar().ToString();
- if (ws.Cells[j + 2, i + 1].Value != null)
- {
- data[j - 1, i] = ws.Cells[j + 2, i + 1].Value.ToString();
- if((!data[j-1,i].Contains("/") || !data[j - 1, i].Contains("-")) && (DataType == "datetime"))
- {
- data[j - 1, i] = "2018-01-01 00:00:00.000";
- }
- if(data[j - 1, i].ToUpper() == "NULL" && DataType == "datetime")
- {
- data[j - 1, i] = "2018-01-01 00:00:00.000";
- }
- if(data[j-1,i].ToUpper() == "NULL" && DataType == "date")
- {
- data[j - 1, i] = "01/01/2018";
- }
- if(data[j - 1, i].ToUpper() == "NULL" && DataType == "smalldatetime")
- {
- data[j - 1, i] = "2018-01-01 00:00:00";
- }
- if(data[j-1,i].Contains("Ox") && (DataType == "int" || DataType == "tinyint") || DataType == "decimal")
- {
- data[j - 1, i] = "0";
- }
- }
- else
- {
- if (DataType == "int" || DataType == "tinyint" || DataType == "decimal" || DataType == "numeric")
- {
- data[j - 1, i] = "0";
- }
- else if (DataType == "nvarchar" || DataType == "varchar")
- {
- data[j - 1, i] = " ";
- }
- else if (DataType == "date")
- {
- data[j - 1, i] = "01/01/2018";
- }
- else if (DataType == "datetime")
- {
- data[j - 1, i] = "2018-01-01 00:00:00.000";
- }
- else if(DataType == "smalldatetime")
- {
- data[j - 1, i] = "2018-01-01 00:00:00";
- }
- else if (DataType == "uniqueidentifier")
- {
- data[j - 1, i] = "00000000-0000-0000-0000-000000000000";
- }
- else
- {
- data[j - 1, i] = "0";
- }
- }
- }
- }
- for (int j = 1; j <= aRange.Rows.Count - 1; j++)
- {
- string insertCom = "insert into [" + tablename + "] ( ";
- string ValuesInsert = " Values(";
- for (int i = 0; i < count; i++)
- {
- insertCom += "[" + headers[i] + "]" + ",";
- ValuesInsert += "'" + data[j - 1, i] + "'" + ",";
- }
- insertCom = insertCom.Remove(insertCom.Length - 1);
- ValuesInsert = ValuesInsert.Remove(ValuesInsert.Length - 1);
- insertCom += ")";
- ValuesInsert += ")";
- insertCom += ValuesInsert;
- SqlCommand sqlcom = new SqlCommand(insertCom, cnn);
- try
- {
- sqlcom.ExecuteNonQuery();
- }
- catch (SqlException ex)
- {
- t.Abort();
- if (ex.Message.Contains("Violation of PRIMARY KEY constraint"))
- {
- MessageBox.Show("Existe valores repetidos no excel ou na base de dados");
- }
- else
- {
- MessageBox.Show("Não foi possivel Converter valores\nLinha " + j.ToString(), "ERRO", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- verif = true;
- }
- }
- }
- t.Abort();
- app.Quit();
- cnn.Close();
- if (verif == false)
- {
- MessageBox.Show("Importado com sucesso");
- }
- else
- {
- MessageBox.Show("Nem tudo foi importado com sucesso");
- }
- }
- private void SetConnectionString()
- {
- connectionString = null;
- if (username != "" && password != "")
- {
- connectionString = @"Data Source=" + servidor + ";" + " Initial Catalog="
- + db + "; User ID=" + username + "; Password=" + password;
- }
- else
- {
- connectionString = @"Data Source=" + servidor + " ;" + " Initial Catalog="
- + db;
- }
- if(cboAutentic.SelectedIndex == 0)
- {
- connectionString += "; Trusted_Connection=True";
- }
- }
- private void BtnExport_Click(object sender, EventArgs e)
- {
- if (lbExport.Items.Count != 0) {
- Thread t = new Thread(new ThreadStart(SplashStart));
- t.Start();
- Thread.Sleep(8000);
- int count = 0;
- int repeatedNames = 0;
- List<String> nomeTabela = new List<string>();
- foreach (string nome in lbExport.Items)
- {
- nomeTabela.Add(nome);
- }
- Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application
- {
- Visible = false
- };
- SqlConnection cnn = new SqlConnection(connectionString);
- Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
- object MissingValue = System.Reflection.Missing.Value;
- foreach (string tableName in nomeTabela)
- {
- string excelName = null;
- int numCar = 0;
- List<string> headers = new List<string>();
- SqlDataAdapter sda = new SqlDataAdapter("Select * FROM [" + tableName + "]", cnn);
- DataTable dt = new DataTable();
- dt.Clear();
- sda.Fill(dt);
- Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet;
- if (count != lbExport.Items.Count - 1)
- {
- wb.Worksheets.Add(ws);
- }
- ws.Cells[1][1] = tableName;
- int countNumVezes = 0;
- for (int i = 0; i < dt.Columns.Count; i++)
- {
- cnn.Open();
- SqlCommand sqlcom = new SqlCommand("select is_identity from sys.columns where OBJECT_ID = OBJECT_ID('" + tableName + "') and name = '" + dt.Columns[i].ColumnName + "';", cnn);
- object isIncremental = sqlcom.ExecuteScalar();
- if (!(Convert.ToBoolean(isIncremental)) && (dt.Columns[i].ColumnName != "timestamp"))
- {
- ws.Cells[2, i + 1 - countNumVezes] = dt.Columns[i].ColumnName;
- headers.Add(dt.Columns[i].ColumnName);
- }
- else
- {
- countNumVezes++;
- }
- cnn.Close();
- }
- ws.Columns.AutoFit();
- if (tableName.ToLower().Contains("history") == true)
- {
- tableName.Replace("history", "xxxxxxx");
- }
- foreach (char letra in tableName.ToCharArray())
- {
- if (letra == '\\' || letra == '/' || letra == '?' || letra == '*')
- {
- excelName += "_";
- }
- else if (numCar == 30)
- {
- goto KeepGoing;
- }
- else
- {
- excelName += letra;
- }
- numCar++;
- }
- KeepGoing:
- try
- {
- //atribuição de um nome á worksheet
- ws.Name = excelName;
- }//Se o nome já foi atribuido ele acrescenta-lhe um numero
- catch (System.Runtime.InteropServices.COMException)
- {
- int tamanho = excelName.Length;
- ws.Name = excelName.Insert(tamanho, repeatedNames.ToString());
- repeatedNames++;
- }
- if (count == 0)
- {
- //abre o dialogo e guarda o excel no caminho indicado
- SFD.ShowDialog();
- wb.SaveAs(SFD.FileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, MissingValue, MissingValue, MissingValue, MissingValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, MissingValue, MissingValue, MissingValue, MissingValue, MissingValue);
- }
- //Conta o nº de tabelas
- count++;
- }
- //fechar a coneccão com a base de dados
- cnn.Close();
- //fecha o workbook
- wb.Close(true, MissingValue, MissingValue);
- //fecha a aplicação excel
- app.Quit();
- //Guarda no excel as ulltimas tabelas exportadas
- SaveToXML(nomeTabela);
- t.Abort();
- MessageBox.Show("Exportado com Sucesso");
- }
- else
- {
- MessageBox.Show("Não tem tabelas para exportar");
- }
- }
- private void SaveToXML(List<string> TableName)
- {
- bool ExistFile = File.Exists("LastTablesExported.xml");
- bool TablesExpFromDb = false;
- XmlDocument xmlDoc = new XmlDocument();
- XmlElement rootNode;
- if (ExistFile == true)
- {
- xmlDoc.Load("LastTablesExported.xml");
- rootNode = xmlDoc.DocumentElement;
- foreach (XmlNode node in xmlDoc.SelectNodes("//DataBase"))
- {
- if (node.Attributes[0].Value.ToString() == db)
- {
- TablesExpFromDb = true;
- goto KeepGoing;
- }
- }
- }
- else
- {
- rootNode = xmlDoc.CreateElement("Tables");
- xmlDoc.AppendChild(rootNode);
- }
- KeepGoing:
- if (TablesExpFromDb == false)
- {
- dbNode = xmlDoc.CreateElement("DataBase");
- XmlAttribute dataBase = xmlDoc.CreateAttribute("db");
- dataBase.Value = db;
- rootNode.AppendChild(dbNode);
- dbNode.Attributes.Append(dataBase);
- foreach (string nomeTabela in TableName)
- {
- XmlNode Table = xmlDoc.CreateElement("Table");
- XmlAttribute ExportedTables = xmlDoc.CreateAttribute("nome");
- ExportedTables.Value = nomeTabela;
- Table.Attributes.Append(ExportedTables);
- dbNode.AppendChild(Table);
- }
- }
- else
- {
- foreach (XmlNode node in xmlDoc.SelectNodes("//DataBase"))
- {
- if (node.Attributes[0].Value.ToString() == db)
- {
- node.RemoveAll();
- XmlAttribute dataBase = xmlDoc.CreateAttribute("db");
- dataBase.Value = db;
- node.Attributes.Append(dataBase);
- foreach (string nomeTabela in TableName)
- {
- XmlNode Table = xmlDoc.CreateElement("Table");
- XmlAttribute ExportedTables = xmlDoc.CreateAttribute("nome");
- ExportedTables.Value = nomeTabela;
- Table.Attributes.Append(ExportedTables);
- node.AppendChild(Table);
- }
- }
- }
- }
- xmlDoc.Save("LastTablesExported.xml");
- }
- private void BtnDelete_Click(object sender, EventArgs e)
- {
- lbExport.Items.Remove(lbExport.SelectedItem);
- }
- private void BtnAdd_Click(object sender, EventArgs e)
- {
- int selectedCells = dgvTables.SelectedCells.Count;
- for (int i = 0; i < selectedCells; i++)
- {
- lbExport.Items.Add(dgvTables.SelectedCells[i].Value.ToString());
- }
- }
- private void LoadConf()
- {
- try
- {
- XmlDocument FXML = new XmlDocument();
- FXML.Load("conf.xml");
- servidor = null;
- db = null;
- username = null;
- password = null;
- foreach (XmlNode node in FXML.SelectNodes("Configuracao"))
- {
- servidor = node.Attributes[0].Value.ToString();
- db = node.Attributes[1].Value.ToString();
- username = node.Attributes[2].Value.ToString();
- password = node.Attributes[3].Value.ToString();
- }
- txtServer.Text = servidor;
- txtDb.Text = db;
- txtUser.Text = username;
- txtPass.Text = password;
- }
- catch (Exception)
- {
- }
- }
- private void btnConf_Click(object sender, EventArgs e)
- {
- if (IsConnected == true)
- {
- dgvTables.Visible = false;
- lbExport.Visible = false;
- btnDelete.Visible = false;
- btnAdd.Visible = false;
- btnExport.Visible = false;
- lblExpTitle.Visible = false;
- btnImport.Visible = false;
- lblImpTitle.Visible = false;
- btnExportData.Visible = false;
- btnUpdate.Visible = false;
- gbConf.Visible = true;
- }
- }
- private void btnExportMenu_Click(object sender, EventArgs e)
- {
- if (IsConnected == true)
- {
- gbConf.Visible = false;
- btnImport.Visible = false;
- lblImpTitle.Visible = false;
- //Metodos
- LoadConf();
- GetTables();
- btnExportData.Visible = true;
- dgvTables.Visible = true;
- lbExport.Visible = true;
- btnDelete.Visible = true;
- btnAdd.Visible = true;
- btnExport.Visible = true;
- lblExpTitle.Visible = true;
- btnUpdate.Visible = true;
- }
- }
- private void btnImportMenu_Click(object sender, EventArgs e)
- {
- if (IsConnected == true)
- {
- dgvTables.Visible = false;
- lbExport.Visible = false;
- btnDelete.Visible = false;
- btnAdd.Visible = false;
- btnExport.Visible = false;
- lblExpTitle.Visible = false;
- gbConf.Visible = false;
- btnExportData.Visible = false;
- btnUpdate.Visible = false;
- btnImport.Visible = true;
- lblImpTitle.Visible = true;
- }
- }
- //usado para movimentar o form
- public const int WM_NCLBUTTONDOWN = 0xA1;
- public const int HT_CAPTION = 0x2;
- [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
- public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
- [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
- public static extern bool ReleaseCapture();
- private void panelTop_MouseDown(object sender, MouseEventArgs e)
- {
- if (e.Button == MouseButtons.Left)
- {
- ReleaseCapture();
- SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement