i'm not good in asking sorry
in my windows application , i have a gridview with data , Here i want to export gridview to excel ,I'm trying with below code
i have a problem with my code to export dataGridView to excel sheet i get the result like that (???%$^&$$&$%&$%^$#%##%##%)
i hope any one can help me with that code
i search about it many time and didn't found any answer
have no idea what collation the tables are set to. Is there a way to export the data correctly, or convert it to the correct encoding?
export button
private void Btexport_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
try
{
// Bind Grid Data to Datatable
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText, col.ValueType);
}
int count = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (count < dataGridView1.Rows.Count - 1)
{
dt.Rows.Add();
foreach (DataGridViewCell cell in row.Cells)
{
dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
}
}
count++;
}
// Bind table data to Stream Writer to export data to respective folder
StreamWriter wr = new StreamWriter(#"C:\Users\ils\Desktop\New folder (2)\Book1.xls");
// Write Columns to excel file
for (int i = 0; i < dt.Columns.Count; i++)
{
wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (dt.Rows.Count); i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (dt.Rows[i][j] != null)
{
wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
}
else
{
wr.Write("\t");
}
}
wr.WriteLine();
}
wr.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}
data
public void Disp_data()
{
SqlConnection mycon = new SqlConnection("Data Source=DESKTOP-J7D5POF;Initial Catalog=ilswork;Persist Security Info=True;User ID=test;Password=12345;Connect Timeout=60");
mycon.Open();
SqlCommand cmd = mycon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select name1 from [dbo].[test5]";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
mycon.Close();
}
private void Form3_Load(object sender, EventArgs e)
{
Disp_data();
}
}
Related
I'm making a desktop application using the windows form with C#, I stored uploaded csv data with data grid view, then I make a transpose feature in the application, but did not work well, because the row of index or row 0 does not included in transpose output file.
Picture 1
So, I decided to add a empty row inside csv file at the top of data with this code
DataRow dr1 = dt.NewRow();
dt.Rows.InsertAt(dr1, 0);
I tried manually by insert empty row in csv and the application look like this
Picture 2
How should I code to make application insert an empty data row at 0 and store it in data grid view looks like a picture above? so my transpose feature works well
here I wrote to store the data in data grid
public DataSet ConnectCSV()
{
DataSet ds = new DataSet();
string fileName = openFileDialogCSVFilePath.FileName;
CsvReader reader = new CsvReader(fileName);
ds = reader.RowEnumerator;
dGridCSVdata.DataSource = ds;
dGridCSVdata.DataMember = "TheData";
return ds;
}
private void dGridCSVdata_Navigate(object sender, NavigateEventArgs ne)
{
}
here I wrote to read the data
public DataSet RowEnumerator
{
get
{
if (null == __reader)
throw new System.ApplicationException("I can't start reading without CSV input.");
__rowno = 0;
string sLine;
string sNextLine;
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("TheData");
DataRow dr1 = dt.NewRow();
dt.Rows.InsertAt(dr1, 0);
while (null != (sLine = __reader.ReadLine()))
{
while (rexRunOnLine.IsMatch(sLine) && null != (sNextLine = __reader.ReadLine()))
sLine += "\n" + sNextLine;
__rowno++;
DataRow dr = dt.NewRow();
string[] values = rexCsvSplitter.Split(sLine);
for (int i = 0; i < values.Length; i++)
{
values[i] = Csv.Unescape(values[i]);
if (__rowno == 1)
{
dt.Columns.Add(values[i].Trim());
}
else
{
if (Csv.CharNotAllowes(values[i]))
{
dr[i] = values[i].Trim();
}
}
}
if (__rowno != 1)
{
dt.Rows.Add(dr);
}
ds.Tables.Add(Transposer.Transpose(dt));
// transpose code
StringBuilder sb = new StringBuilder();
for (int u = 0; u < dt.Columns.Count; u++)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
sb.Append(dt.Rows[i][u].ToString());
if (i < dt.Rows.Count - 1)
{
sb.Append(',');
}
}
sb.AppendLine();
}
File.WriteAllText("C:\\Users\\Desktop\\Output.csv", sb.ToString());
}
__reader.Close();
return ds;
}
}
I'm trying to loop over the datatable and create word table. So far if I have 3 rows in the datatable they are being inserted into the first row of my Microsoft Word table, instead I want every row from the datatable into a new row in Microsoft Word table.
Below is my code :
protected void Button2_Click(object sender, EventArgs e)
{
PullData();
gvd2.DataSource = dataTable;
gvd2.DataBind();
// Create a document.
using (DocX document = DocX.Create(#"D:\Test.docx"))
{
// Add a Table to this document.
Novacode.Table t = document.AddTable(2, 3);
// Specify some properties for this Table.
t.Alignment = Alignment.center;
t.Design = TableDesign.MediumGrid1Accent2;
// Add content to this Table.
t.Rows[0].Cells[0].Paragraphs.First().Append("A");
//foreach (DataRow row in dataTable.Rows)
//{
// t.Rows[1].Cells[0].Paragraphs.First().Append(row["IssueSubjectType"].ToString());
//}
// Loop through the rows in the Table and insert data from the data source.
for (int row = 1; row < t.RowCount; row++)
{
for (int cell = 0; cell < t.Rows[row].Cells.Count; cell++)
{
Paragraph cell_paragraph =t.Rows[row].Cells[cell].Paragraphs[0];
cell_paragraph.InsertText(dataTable.Rows[row - 1].ItemArray[cell].ToString(), false);
}
}
// Insert the Table into the document.
document.InsertTable(t);
// Save the Document.
document.Save();
// Release this document from memory.
document.Dispose();
}
}
private DataTable dataTable = new DataTable();
// method to pull data from database to datatable
public void PullData()
{
using (SqlConnection sqlConn = new SqlConnection("Data Source=.;Initial Catalog=UAE_OG-Interanl;Integrated Security=True"))
{
string sqlQuery = #"SELECT IssueSubjectType from tbl_IssueStoPublicate WHERE IssueNumber = '625' order by IssueSubjectOrder desc";
using (SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
{
SqlDataAdapter ds = new SqlDataAdapter(cmd);
ds.Fill(dataTable);
}
}
}
Any help would be a lifesaver.
https://github.com/xceedsoftware/DocX/blob/master/Examples/Samples/Table/TableSample.cs
int size = 3;
DocX docX = DocX.Create(result, DocumentTypes.Document);
Table table = docX.AddTable(size, size);
table.AutoFit = AutoFit.Contents;
for (int i = 0; i <= (int)TableBorderType.InsideV; i++)
table.SetBorder((TableBorderType)i, new Border());
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
table.Rows[i].Cells[j].Paragraphs[0].InsertText(i + " | " + j);
docX.InsertParagraph().InsertTableBeforeSelf(table);
docX.Save();
I have a gridview in .net which needs to be exported to excel/datable.Problem is
it contains textbox+dropdowns. This does not work for dropdowns
public void Persist(object sender, EventArgs e)
{
// GridViewExportUtil.Export("Customers.xls", this.grdData);
DataTable dt = new DataTable();
// add the columns to the datatable
if (grdData.HeaderRow != null)
{
for (int i = 0; i < grdData.HeaderRow.Cells.Count; i++)
{
dt.Columns.Add(grdData.HeaderRow.Cells[i].Text);
}
}
// add each of the data rows to the table
foreach (GridViewRow row in grdData.Rows)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dr[i] = row.Cells[i].Text.ToString();
}
dt.Rows.Add(dr);
}
i'm c# programmer. At present, i am try to add some 3 of 5 columns (fileId, filePath, authorName, fileContent, DateSend) in sql data in the datagrid-viewer ; the fileId and fileContent column are hidden. Thank you very much!
con = new SqlConnection("Data Source=LEO-PC\\SQLEXPRESS;Initial Catalog = datashare;Integrated Security = True");
cmd = new SqlCommand("select * from maintable", con);
con.Open();
SqlDataReader sqlRead;
try
{
sqlRead = cmd.ExecuteReader();
while (sqlRead.Read())
{
//Adding to datagrid
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
To hide the 2 fields create a OnRowCreated event in the grid:
OnRowCreated="gridView1_RowCreated"
Remember to populate the grid using the
SqlDataReader reader = cmd.ExecuteReader();
gridView1.DataSource = reader;
and the gridview must have property must be AutoGeneretedColumns = "true"
Then create the event as follow:
protected void gridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
DataControlFieldCell cell =
(DataControlFieldCell) e.Row.Cells[i];
if (cell.ContainingField.HeaderText == "fileId")
{
e.Row.Cells[i].Visible = false;
cell.Visible = false;
}
if (cell.ContainingField.HeaderText == "fileContent")
{
e.Row.Cells[i].Visible = false;
cell.Visible = false;
}
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
DataControlFieldCell cell =
(DataControlFieldCell) e.Row.Cells[i];
if (cell.ContainingField.ToString() == "fileId")
{
cell.Visible = false;
}
if (cell.ContainingField.ToString() == "fileContent")
{
cell.Visible = false;
}
}
}
}
This might not be the most effecient way but it serve the purpose using code. One should be able to hide the columns using the gridview template when the columns are bound.
for (int i = 0; i < form2.dataGridView1.Rows.Count; i++)
{
if ( form2.dataGridView2.Rows[i].Cells[0].Value != null &&
(bool) form2.dataGridView2.Rows[i].Cells[0].Value == true )
{
form2.dataGridView2.Rows.Add();
for (int j = 1; j < form2.dataGridView1.Columns.Count; j++)
form2.dataGridView2.Rows[i].Cells[j].Value =
form2.dataGridView1.Rows[i].Cells[j].Value;
}
}
the above code is not giving any result. please tell me how to copy the data of one datagridview to another?
Check Copy from datagridview and paste to second datagridview.
Also, you can do as the following:
//Bind datagridview to linq
var gd1 =
( from a in datagridview.Rows.Cast<DataGridViewRow>()
select new {Column1 = a.Cells["Column1"].Value.ToString() }).tolist();
//loop dg1 and save it to datagridview2
foreach(var b in dg1)
{
datagridview2.Rows.Add(b.Column1);
}
Regards
In form1 copy this code
private void Form1_Load(object sender,EventArgs e)
{
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.Columns.Insert(0, new DataGridViewCheckBoxColumn());
show_chkBox();
SqlConnection con = new SqlConnection("server=(local);DataBase=RIMS;User
d=sa;Password=Rootdb");
SqlCommand com = new SqlCommand("Select * from Master_City", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds, "city");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "city";
}
private void button1_Click_1(object sender, EventArgs e)
{
DataGridViewRow dr = dataGridView1.SelectedRows[0];
dtItems.Columns.Add("city_ID");
dtItems.Columns.Add("city_Name");
dtItems.Columns.Add("status");
dtItems.Columns.Add("date");
if (dataGridView1.Rows.Count > 1)
{
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value != null)
{
DataRow row;
row = dtItems.NewRow();
row["city_ID"] = dataGridView1.Rows[i].Cells[1].Value.ToString();
row["city_Name"] = dataGridView1.Rows[i].Cells[2].Value.ToString();
row["status"] = dataGridView1.Rows[i].Cells[3].Value.ToString();
row["date"] = dataGridView1.Rows[i].Cells[4].Value.ToString();
dtItems.Rows.Add(row);
}
}
}
Form2 frm = new Form2(dtItems);
frm.ShowDialog();
}
in form2 copy this code..
public Form2(DataTable dtIt)
{
dtItems = dtIt;
InitializeComponent();
}
private void AddEmptyRows()
{
for (int i = 1; i <= 5; i++)
{
dataGV.Rows.Add();
}
}
private void Form2_Load(object sender, EventArgs e)
{
AddEmptyRows();
for (int i = 0; i < dtItems.Rows.Count; i++)
{
dataGV.Rows[i].Cells[0].Value = dtItems.Rows[i]["city_ID"];
dataGV.Rows[i].Cells[1].Value = dtItems.Rows[i]["city_Name"];
dataGV.Rows[i].Cells[2].Value = dtItems.Rows[i]["status"];
dataGV.Rows[i].Cells[3].Value = dtItems.Rows[i]["date"];
}
dataGV.Enabled = true;
}
Mirror Data From one Data View into Another Data View
If you just want to mirror the data from one DataGridView in another one. For example: DataGridView1 mirror data in DataGridView2.
DataGridView2.DataSource = DataGridView1.DataSource;
Remember this will only mirror the data from on DataGridView in another one.