我正在尝试将
.xlsx
文件导入数据库。我在导入函数中遇到问题:我调用了一个函数来创建一行中的元素列表,每行中包含每个单元格的列表,我无法识别某些单元格何时为空。
提前感谢您的帮助和兴趣!
这是完整代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
//using Excel Microsoft.Office.Interop.Excel;
using System.Reflection;
//#using dracia dracu;
namespace WindowsFormsApp1
{
public partial class zTool : Form
{
BackgroundWorker worker = new BackgroundWorker();
public zTool()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// pick a file/ chose a file
string filePath = OpenFilePicker();
//pun calea intr-un string
if (filePath != null)
{
// verific string ul sa nu fie null
textBox1.Text = filePath;
// completez casuta de path cu calea aleasa
}
else
{
MessageBox.Show("Alege un fisier de import!");
//afisez mesaj de eroare in caz ca butonul a fost apasat insa nu a fost ales nici un fisier';
}
}
public string OpenFilePicker()
{
//deschide fereastra de selectie document;
OpenFileDialog filePicker = new OpenFileDialog();
filePicker.Title = "Select a File";
filePicker.Filter = "All files (*.*)|*.*";
if (filePicker.ShowDialog() == DialogResult.OK)
{
return filePicker.FileName;
}
else
{
return null;
}
}
private void button3_Click(object sender, EventArgs e)
{
//check db connection button
//ShowProgressBar();
// this is the connection string , with this one we connect via sqlConnection property from below
string connectionString = "Data Source=192.168.180.15;Initial Catalog=Localize_Hercules;User ID=sa;Password=UniDB!Admin;";
SqlConnection connection = new SqlConnection(connectionString);
try
{
connection.Open();
MessageBox.Show("Connection successful!");
}
catch (Exception ex)
{
MessageBox.Show("Connection failed: Conexiunea nu s-a putut realiza. Verifica VPN ul! Eroare la conectare: " + ex.Message);
}
finally
{
connection.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
string connectionString2 = "Data Source=192.168.180.15;Initial Catalog=Localize_Hercules;User ID=sa;Password=UniDB!Admin;";
ImportExcelFile(textBox1.Text, connectionString2);
}
public void ImportExcelFile(string filePath, string connectionString)
{
int nrDeRanduriInserate = 0;
try
{
// Open the Excel file for reading
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filePath, false))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
Worksheet worksheet = worksheetPart.Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
// Open a database connection
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
bool isFirstRow = true; // flag variable to skip the first row
// Loop through each row in the Excel file
foreach (Row row in sheetData.Elements<Row>())
{
if (!isFirstRow) // check if this is not the first row
{
// Extract the values from each cell in the row
List<string> cellValues = GetCellValues(workbookPart, row);
// Insert the values into the database using parameterized queries
string sql = "INSERT INTO DICTIONARYIMP (ID, RESTEXT, TRANS01, TRANS02) VALUES (@Value1, @Value2, @Value3, @Value4)";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@Value1", string.IsNullOrEmpty(cellValues[0]) ? DBNull.Value : (object)cellValues[0]);
//MessageBox.Show(cellValues[0]);
command.Parameters.AddWithValue("@Value2", string.IsNullOrEmpty(cellValues[1]) ? DBNull.Value : (object)cellValues[1]);
// MessageBox.Show(cellValues[1]);
//aici crapa;
command.Parameters.AddWithValue("@Value3", string.IsNullOrEmpty(cellValues[2]) ? DBNull.Value : (object)cellValues[2]);
// MessageBox.Show(cellValues[2]);
//
command.Parameters.AddWithValue("@Value4", string.IsNullOrEmpty(cellValues[3]) ? DBNull.Value : (object)cellValues[3]);
//MessageBox.Show(cellValues[3]);
nrDeRanduriInserate += command.ExecuteNonQuery();
//command.ExecuteNonQuery();
}
}
else
{
isFirstRow = false; // set the flag to false after reading the first row
}
}
}
}
}
catch (Exception ex)
{
//
MessageBox.Show("Importul a fost efectuat! " + "S-au importat " + nrDeRanduriInserate.ToString() + " linii! " + "Cod eroare de confirmare: " + ex.Message);
//de verificat de ce nu scap de string or bynary data pentru ultimul rand;
}
}
private static List<string> GetCellValues(WorkbookPart workbookPart, Row row)
{
List<string> cellValues = new List<string>();
foreach (Cell cell in row.Elements<Cell>())
{
// here i need help to identify the empty cell;
if (cell == null
// (string.IsNullOrEmpty(cell.InnerText) == true)
// ||
// (string.IsNullOrWhiteSpace(cell.CellValue) == true) ||
// (string.IsNullOrWhiteSpace(cell.InnerText) == true) ||
// cell.InnerText == "" ||
// cell.CellValue == null ||
// cell.InnerText == null ||
// cell.CellValue.InnerText == ""
)
{
MessageBox.Show("celula goala"+ cell.CellValue);
// Cell value is empty, add "null" to cell values list
cellValues.Add("null");
}
else
{
string cellValue = cell.InnerText; // Define cellValue variable here
if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
{
var sharedStringTable = workbookPart.SharedStringTablePart.SharedStringTable;
int index = int.Parse(cellValue);
cellValue = sharedStringTable.ElementAt(index).InnerText;
}
cellValues.Add(cellValue);
}
}
return cellValues;
}
private void button4_Click(object sender, EventArgs e)
{
// Connection string to database
string connectionString = "Data Source=192.168.180.15;Initial Catalog=Localize_Hercules;User ID=sa;Password=UniDB!Admin;";
// Name of the table we want to delete data from
string tableName = "DICTIONARYIMP";
try
{
//we connect to the database;
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Open the connection
connection.Open();
// Create a SQL command to delete all records from the table
string sql = "delete from " + tableName;
//execute the command
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.ExecuteNonQuery();
}
// Display a message indicating the data was deleted successfully
MessageBox.Show("Liniile din tabela DICTIONARYIMP au fost sterse!");
}
}
catch (Exception ex)
{
// afisez mesajele de eroare;
MessageBox.Show("Eroare stergere date: " + ex.Message);
}
}
private void button5_Click(object sender, EventArgs e)
{
int nrDeRanduriUpdatate = 0;
string connectionString = "Data Source=192.168.180.15;Initial Catalog=Localize_Hercules;User ID=sa;Password=UniDB!Admin;";
try
{
//we connect to the database;
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Open the connection
connection.Open();
// Create a SQL command to delete all records from the table
string sql = "UPDATE FD SET FD.TRANS02=FI.TRANS02 FROM DICTIONARY FD INNER JOIN DICTIONARYIMP FI ON FD.ID=FI.ID AND FI.TRANS02!='NULL' AND FI.TRANS02!='' AND FI.ID!=''";
//execute the command
using (SqlCommand command = new SqlCommand(sql, connection))
{
nrDeRanduriUpdatate += command.ExecuteNonQuery();
//command.ExecuteNonQuery();
}
// Display a message indicating the data was deleted successfully
MessageBox.Show("Au fost sincronizate liniile din DICTIONARYIMP cu cele din DICTIONARY! Nr linii updatate: " + nrDeRanduriUpdatate);
}
}
catch (Exception ex)
{
// afisez mesajele de eroare;
MessageBox.Show("Eroare sincronizare date: " + ex.Message);
}
}
private void button6_Click(object sender, EventArgs e)
{
// Connect to your database
SqlConnection conn = new SqlConnection("Data Source = 192.168.180.15; Initial Catalog = Localize_Hercules; User ID = sa; Password = UniDB!Admin; ");
// Create a SQL query to retrieve data
string query = "SELECT * FROM DICTIONARYIMP";
// Create a SqlDataAdapter object to fill the DataGridView
SqlDataAdapter da = new SqlDataAdapter(query, conn);
// Create a DataTable object to hold the data
DataTable dt = new DataTable();
// Fill the DataTable with the data from the database
da.Fill(dt);
// Set the DataSource property of the DataGridView to the DataTable
dataGridView1.DataSource = dt;
}
}
}
我尝试使用指令使用 Excel Microsoft.Office.Interop.Excel;但我未能从 NuGet 包中安装 dll。我找到了替代指令:
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
我使用以下属性来确定单元格是否为空:
if (cell == null
//(string.IsNullOrEmpty(cell.InnerText) == true)
//||
//(string.IsNullOrWhiteSpace(cell.CellValue) == true) ||
// (string.IsNullOrWhiteSpace(cell.InnerText) == true) ||
// cell.InnerText == "" ||
// cell.CellValue == null ||
// cell.InnerText == null ||
// cell.CellValue.InnerText == ""
)