I want to strip all formatting (borders etc) from an Excel file when it is loaded before it fills the data into a data table.
When i run my code, the updateExcel_Click
part updates column C with what is in ConsigneeCombo
box for each row, however if the file i am processing has formatting, for example 10 rows with borders but only 8 of them rows with text it updates all 10 because of the formatting
EDIT
Rather than stripping out the borders, what about in the updateExcel_Click
part only adding it to rows that have text in?
private void updateExcel_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
dataGridView1[2, i].Value = ConsigneeCombo.Text;
}
}
My current GetData code is:
private DataTable GetData(string userFileName)
{
string dirName = Path.GetDirectoryName(userFileName);
string fileName = Path.GetFileName(userFileName);
string fileExtension = Path.GetExtension(userFileName);
string connection = string.Empty;
string query = string.Empty;
switch (fileExtension)
{
case ".xls":
connection = $@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={userFileName};" +
"Extended Properties=\"Excel 8.0; HDR=Yes; IMEX=1\"";
string sheetNamexls;
using (OleDbConnection con = new OleDbConnection(connection))
{
con.Open();
var dtSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
sheetNamexls = dtSchema.Rows[0].Field<string>("TABLE_NAME");
}
if (sheetNamexls.Length <= 0) throw new InvalidDataException("No sheet found.");
query = $"SELECT * FROM [{sheetNamexls}]";
break;
case ".xlsx":
connection = $@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={userFileName};" +
"Extended Properties=\"Excel 12.0; HDR=Yes; IMEX=1\"";
string sheetName;
using (OleDbConnection con = new OleDbConnection(connection))
{
con.Open();
var dtSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
sheetName = dtSchema.Rows[0].Field<string>("TABLE_NAME");
}
if (sheetName.Length <= 0) throw new InvalidDataException("No sheet found.");
query = $"SELECT * FROM [{sheetName}]";
break;
case ".csv":
connection = $@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={dirName};" +
"Extended Properties=\"text; HDR=Yes; IMEX=1; FMT=Delimited\"";
query = $"SELECT * FROM [{fileName}]";
break;
}
return FillData(connection, query);
}
I have tried adding the ClearFormats();
method but cannot get it to work.
Full code:
using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace DrayIn
{
public partial class DrayIn : Form
{
public DrayIn()
{
InitializeComponent();
using (SqlConnection sqlConnection = new SqlConnection("ConnDetails"))
{
SqlCommand sqlCmd = new SqlCommand(@"SELECT Id
FROM ref_bizunit_scoped sh
WHERE sh.role = 'SHIPPER'
AND sh.Life_Cycle_State = 'ACT'
ORDER BY ID", sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
ConsigneeCombo.Items.Add(sqlReader["Id"].ToString());
}
sqlReader.Close();
}
ConsigneeCombo.SelectedIndex = 0;
}
private DataTable FillData(string connection, string query)
{
DataTable dataTable = new DataTable();
using (OleDbConnection con = new OleDbConnection(connection))
{
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(dataTable);
adapter.Dispose();
};
return dataTable;
}
private DataTable GetData(string userFileName)
{
string dirName = Path.GetDirectoryName(userFileName);
string fileName = Path.GetFileName(userFileName);
string fileExtension = Path.GetExtension(userFileName);
string connection = string.Empty;
string query = string.Empty;
switch (fileExtension)
{
case ".xls":
connection = $@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={userFileName};" +
"Extended Properties=\"Excel 8.0; HDR=Yes; IMEX=1\"";
string sheetNamexls;
using (OleDbConnection con = new OleDbConnection(connection))
{
con.Open();
var dtSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
sheetNamexls = dtSchema.Rows[0].Field<string>("TABLE_NAME");
}
if (sheetNamexls.Length <= 0) throw new InvalidDataException("No sheet found.");
query = $"SELECT * FROM [{sheetNamexls}]";
break;
case ".xlsx":
connection = $@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={userFileName};" +
"Extended Properties=\"Excel 12.0; HDR=Yes; IMEX=1\"";
string sheetName;
using (OleDbConnection con = new OleDbConnection(connection))
{
con.Open();
var dtSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
sheetName = dtSchema.Rows[0].Field<string>("TABLE_NAME");
}
if (sheetName.Length <= 0) throw new InvalidDataException("No sheet found.");
query = $"SELECT * FROM [{sheetName}]";
break;
case ".csv":
connection = $@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={dirName};" +
"Extended Properties=\"text; HDR=Yes; IMEX=1; FMT=Delimited\"";
query = $"SELECT * FROM [{fileName}]";
break;
}
return FillData(connection, query);
}
private void Browse_Click(object sender, EventArgs e)
{
fileTextBox.Visible = true;
ConsigneeCombo.Visible = true;
updateExcel.Visible = true;
dataGridView1.Visible = true;
saveExcel.Visible = true;
consigneeLabel.Visible = true;
fileLabel.Visible = true;
string userFileNameUT = string.Empty;
string fileExtensionUT = string.Empty;
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
ofd.Filter = "CSV Files|*.csv|Excel '97-2003|*.xls|Excel 2007-2019|*.xlsx";
if (ofd.ShowDialog(this) == DialogResult.OK)
{
fileExtensionUT = Path.GetExtension(ofd.FileName);
userFileNameUT = ofd.FileName;
}
else
{
fileTextBox.Visible = false;
ConsigneeCombo.Visible = false;
updateExcel.Visible = false;
dataGridView1.Visible = false;
saveExcel.Visible = false;
consigneeLabel.Visible = false;
fileLabel.Visible = false;
}
}
string extensionMix = string.Empty;
if (fileExtensionUT == ".csv") extensionMix = ".csv";
else if (fileExtensionUT == ".xls") extensionMix = ".xls";
else if (fileExtensionUT == ".xlsx") extensionMix = ".xlsx";
if (userFileNameUT.Length == 0) return;
string userFileName = Path.Combine(Path.GetDirectoryName(userFileNameUT), Path.GetFileNameWithoutExtension(userFileNameUT.Replace(".", "")) + extensionMix);
File.Copy(userFileNameUT, userFileName, true);
this.dataGridView1.DataSource = GetData(userFileName);
fileTextBox.Text = userFileNameUT;
textBox4.Text = userFileName;
textBox1.Text = Path.GetFileName(userFileNameUT);
}
private void updateExcel_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
dataGridView1[2, i].Value = ConsigneeCombo.Text;
}
}
public void ToCsV(DataGridView dGV, string filename)
{
string stOutput = "";
string sHeaders = "";
for (int j = 0; j < dataGridView1.Columns.Count; j++)
sHeaders = sHeaders.ToString() + Convert.ToString(dataGridView1.Columns[j].HeaderText) + ",";
stOutput += sHeaders + "\r\n";
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
string stLine = "";
for (int j = 0; j < dataGridView1.Rows[i].Cells.Count; j++)
stLine = stLine.ToString() + Convert.ToString(dataGridView1.Rows[i].Cells[j].Value) + ",";
stOutput += stLine + "\r\n";
}
Encoding utf16 = Encoding.GetEncoding(1254);
byte[] output = utf16.GetBytes(stOutput);
FileStream fs = new FileStream(filename, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(output, 0, output.Length);
bw.Flush();
bw.Close();
fs.Close();
}
private void saveExcel_Click_1(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "Save Excel Files";
sfd.CheckPathExists = true;
sfd.DefaultExt = "csv";
sfd.Filter = "Excel Files|*.csv";
string saveFileName = textBox1.Text;
string fileExtensionTrim = Path.GetExtension(saveFileName);
string subFinalSaveName = textBox1.Text;
string finalSaveName = Path.GetFileNameWithoutExtension(subFinalSaveName) + ".csv";
textBox3.Text = finalSaveName;
sfd.FileName = finalSaveName;
sfd.InitialDirectory = @"C:";
if (sfd.ShowDialog() == DialogResult.OK)
{
ToCsV(dataGridView1, sfd.FileName);
string userFileName = textBox4.Text;
File.Delete(userFileName);
fileTextBox.Visible = false;
ConsigneeCombo.Visible = false;
updateExcel.Visible = false;
dataGridView1.Visible = false;
saveExcel.Visible = false;
consigneeLabel.Visible = false;
fileLabel.Visible = false;
}
else
{
fileTextBox.Visible = true;
ConsigneeCombo.Visible = true;
updateExcel.Visible = true;
dataGridView1.Visible = true;
saveExcel.Visible = true;
consigneeLabel.Visible = true;
fileLabel.Visible = true;
}
}
}
}