MVC/C# Export multiple datasets to multiple worksheets Excel - c#

I am using ClosedXML from this example.
Exporting datasets into multiple excel sheets of one excel file
My code is mostly the same. I get ReadTimeOut and WriteTimeOut error and thus, no file is created. .
here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ClosedXML.Excel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Mvc;
namespace MyProject.DAL
{
public class GenerateBook
{
private DataTable get_TblA()
{
using (SqlConnection con = Connection.GetConnection())
{
using (SqlCommand cmd = new SqlCommand("SELECT cola, colB
FROM dbo.tblA;"))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
da.SelectCommand = cmd;
da.Fill(dt);
return dt;
}
}
}
}
private DataTable get_TblB()
{
using (SqlConnection con = Connection.GetConnection())
{
using (SqlCommand cmd = new SqlCommand("SELECT cola, colB
FROM dbo.tblB;"))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
da.SelectCommand = cmd;
da.Fill(dt);
return dt;
}
}
}
}
public DataSet getDataSetExportToExcel()
{
DataSet ds = new DataSet();
DataTable dtEmp = new DataTable("ALM_List_LOB");
dtEmp = getUIP_ALM_List();
DataTable dtEmpOrder = new DataTable("GPR_LOB_CMS_VDN");
dtEmpOrder = getGPR_LOB_CMS_VDN();
ds.Tables.Add(dtEmp);
ds.Tables.Add(dtEmpOrder);
return ds;
}
public DataSet GetDataSetExportToExcel()
{
//use for multiple sps
DataSet ds = new DataSet();
var SPNames = new List<string>() { "storedproc1", "storedproc2" };
foreach (var SPName in SPNames)
{
DataTable dt = new DataTable();
dt = GetDataTableExportToExcel(SPName);
ds.Tables.Add(dt);
}
return ds;
}
private DataTable GetDataTableExportToExcel(string SPName)
{
//use for single sp
DataTable dt = new DataTable();
using (SqlConnection con = Connection.GetConnection())
{
using (var cmd = new SqlCommand(SPName, con))
{
using (var sda = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue()
sda.Fill(dt);
return dt;
}
}
}
}
public ActionResult ExportToExcel()
{
try
{
var sheetNames = new List<string>() { "sheetName1", "sheetName2" };
string fileName = "Example.xlsx";
// for sps DataSet ds = GetDataSetExportToExcel();
DataSet ds = getDataSetExportToExcel();
XLWorkbook wbook = new XLWorkbook();
for (int k = 0; k < ds.Tables.Count; k++)
{
DataTable dt = ds.Tables[k];
IXLWorksheet Sheet = wbook.Worksheets.Add(sheetNames[k]);
for (int i = 0; i < dt.Columns.Count; i++)
{
Sheet.Cell(1, (i + 1)).Value = dt.Columns[i].ColumnName;
}
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
Sheet.Cell((i + 2), (j + 1)).Value = dt.Rows[i][j].ToString();
}
}
}
Stream spreadsheetStream = new MemoryStream();
wbook.SaveAs(spreadsheetStream);
spreadsheetStream.Position = 0;
return new FileStreamResult(spreadsheetStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = fileName };
}
catch(Exception e)
{
throw e;
}
}
public SetToExport(string channel, string assets )
{
ActionResult status = ExportToExcel();
}
}
}
I tried setting them to 0 but did not help. Please guide how to fix
I have tried various samples to achieve this, but none have worked completely Really will appreciate help.

Related

Multi Column comboBox but when select the value should be Id

i have the done following coding, unable to get the it working..
i have a Table with Id, Product, FolderPath.
i have a comboBox2 where i need two column of data from above table "Id" & "Product" to been shown in comboBox2. Now if i select a Row from comboBox2 i need the textBox1 and textBox2 to be filled with "Product" and "FolderPath" based on the comboBox2 selection.
Like even though the comboBox2 shows "Id" & "Product" internally the value has to be "Id".
Following are my code; can someone help me on this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Main : Form
{
string connString;
SqlConnection conn;
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
connString = #"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=ifz001;";
conn = new SqlConnection(connString);
conn.Open();
Load_Products();
}
void Load_Products()
{
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM FileFolderPath", conn);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
comboBox2.Items.Add(dt.Rows[i]["Product"].ToString());
comboBox2.ValueMember = dt.Rows[i]["Id"].ToString();
}
}
catch (Exception lp)
{
MessageBox.Show(lp.Message);
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
/*try
{*/
var pix = "SELECT * FROM FileFolderPath WHERE Id = '" + comboBox2.ValueMember + "'";
SqlCommand cmd = new SqlCommand(pix, conn);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
PID.Text = dr["Product"].ToString();
PPath.Text = dr["FolderPath"].ToString();
}
/*}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}*/
}
Achieved using below code changes:
void Load_Products()
{
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM FileFolderPath", conn);
DataTable dt = new DataTable();
da.Fill(dt);
for(int i = 0; i < dt.Rows.Count; i++)
{
string pid = dt.Rows[i]["Id"].ToString() as string;
string p = dt.Rows[i]["Product"].ToString();
comboBox2.Items.Add(p);
comboBox2.DisplayMember = p;
comboBox2.ValueMember = pid.ToString() as string;
}
}
catch (Exception lp)
{
MessageBox.Show(lp.Message);
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
var ppat = "SELECT * FROM FileFolderPath WHERE Id = '" + comboBox2.SelectedIndex + "' ++1";
SqlCommand cmd = new SqlCommand(ppat, conn);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach(DataRow dr in dt.Rows)
{
PID.Text = dr["Id"].ToString();
PPath.Text = dr["FolderPath"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

C# Paginate SQL result from a proc call

I have the following method that calls a proc in my database and returns the results into a dataset. The dataset is then used to populate a table I render using MVC & cshtml.
The method is:
public DataSet CallProcToDataSet(string procName)
{
DataSet ds = new DataSet();
string constr = ConfigurationManager.ConnectionStrings["UAT"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(procName))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
}
}
}
return ds;
}
This works fine, however what I want is to have some way of paginating the results so that only 10 at a time are displayed. What is the best way for me to achieve this that doesn't involve any changes to the proc calls?
You can use this overload of the Fill method
public int Fill(int startRecord, int maxRecords, params DataTable[] dataTables);
(link: https://msdn.microsoft.com/en-us/library/0z5wy74x(v=vs.110).aspx)
This way you will only return a subset of the records without modifying your stored procedure.
Example (MSTest)
[TestMethod]
public void TestMethod1()
{
DataSet ds = new DataSet();
var procName = "sp_server_info";
string constr = ConfigurationManager.ConnectionStrings["UAT"].ConnectionString;
var tblName = "result";
var tbls = new[] { ds.Tables.Add(tblName) };
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(procName))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(0, 10, tbls);
}
}
}
Assert.AreEqual(tbls[0].Rows.Count, 10);
}
Try following :
DataSet ds = new DataSet();
DataTable dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i += 10)
{
DataTable pageTable = dt.AsEnumerable().Where((x, n) => (n >= i) && (n < i + 10)).CopyToDataTable();
}

export 2 grid views in to a single worksheet in Excel

Currently, I have 2 data tables that are being exported into 2 separate worksheets. How do I export these 2 data tables into a single worksheet? Anyone? I've been having a tough time getting this puzzle solved.
private DataTable SkyvisionMachineData()
{
string constr = ConfigurationManager.ConnectionStrings["Media_OperationsConnectionString9"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT CorporateName, Region FROM MACHINE"))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
da.SelectCommand = cmd;
da.Fill(dt);
dt.TableName = "Region";
return dt;
}
}
}
}
private DataTable SkyvisionZoneData()
{
string constr = ConfigurationManager.ConnectionStrings["Media_OperationsConnectionString9"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT CorporateName, Spare, Region FROM dbo.Machine WHERE CorporateName LIKE #CorporateName OR Region like #Region"))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
Label1.Text = TextBox1.Text;
DataTable dt = new DataTable();
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#CorporateName", SqlDbType.VarChar, 50).Value = Label1.Text;
cmd.Parameters.Add("#Region", SqlDbType.VarChar, 20).Value = Label1.Text;
cmd.Connection = con;
da.SelectCommand = cmd;
da.Fill(dt);
dt.TableName = "Machine";
return dt;
}
}
}
}
public DataSet getDataSetExportToExcel()
{
DataSet ds = new DataSet();
DataTable Machine = new DataTable("Machine Data");
Machine = SkyvisionMachineData();
DataTable Region = new DataTable("Skyvision Zone Data");
Region = SkyvisionZoneData();
ds.Tables.Add(Machine);
ds.Tables.Add(Region);
return ds;
}
protected void ExportToExcel_Click(object sender, EventArgs e)
{
DataSet ds = getDataSetExportToExcel();
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(ds);
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename= DBSearchReport.xlsx
");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
The Merge method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.
If you want to preserve both of the original tables, you could copy the original first, then merge:
dtAll = new DataTable();
...
dtAll.Merge(dtOne);
dtAll.Merge(dtTwo);
dtAll.Merge(dtThree);
This technique is useful in a loop where you want to iteratively merge data tables:
DataTable dtAllCountries = new DataTable();
foreach(String strCountry in listCountries)
{
DataTable dtCountry = getData(strCountry); //Some function that returns a data table
dtAllCountries.Merge(dtCountry);
}

How to connect to database through ODBC

private void Form7_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Integrated Security=true;database=EDIXfer");
SqlDataAdapter da = new SqlDataAdapter("select EDIScheduleID from ETAProcessSchedule", cn);
DataTable dt = new DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
comboBox1.Items.Add(dt.Rows[x][0].ToString());
}
}
The above code is working fine, but in case of OLEDB or ODBC, it's not working (namespaces added for both OLEDB and ODBC).
using System.Data.Odbc;
private void Form7_Load(object sender, EventArgs e)
{
OdbcConnection cn = new OdbcConnection("Integrated Security=true;database=EDIXfer");
OdbcDataAdapter da = new OdbcDataAdapter("select EDIScheduleID from ETAProcessSchedule", cn);
DataTable dt = new DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
comboBox1.Items.Add(dt.Rows[x][0].ToString());
}
}
How to correctly connect to database using ODBC?
This might help,
using (OdbcCommand com = new OdbcCommand(
"SELECT ColumnWord FROM OkieTable WHERE MagicKey = ?", con))
{
com.Parameters.AddWithValue("#var", paramWord);
using (OdbcDataReader reader = com.ExecuteReader())
{
while (reader.Read())
{
string word = reader.GetString(0);
// Word is from the database. Do something with it.
}
}
}

SQLCommand syntax error

I am writing to request some help on my c# syntax. I keep getting syntax in "sda.Fill(dt);" and I can not figure out the reason why.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select distinct Price_type from Price";
DataTable dt = GetData(query);
ddlPrice.DataSource = dt;
ddlPrice.DataTextField = "Price_type";
ddlPrice.DataValueField = "Price_type";
ddlPrice.DataBind();
ddlPrice2.DataSource = dt;
ddlPrice2.DataTextField = "Price_type";
ddlPrice2.DataValueField = "Price_type";
ddlPrice2.DataBind();
ddlPrice2.Items[1].Selected = true;
}
}
protected void Compare(object sender, EventArgs e)
{
string query = string.Format("select price, date from Price where Price_type = '{0}' order by date)", ddlPrice.SelectedItem.Value);
DataTable dt = GetData(query);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
LineChart1.Series.Add(new AjaxControlToolkit.LineChartSeries { Name = ddlPrice.SelectedItem.Value, Data = y });
query = string.Format("select price, date from Price where Price_type = '{0}' order by date)", ddlPrice2.SelectedItem.Value);
dt = GetData(query);
y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
LineChart1.Series.Add(new AjaxControlToolkit.LineChartSeries { Name = ddlPrice2.SelectedItem.Value, Data = y });
LineChart1.CategoriesAxis = string.Join(",", x);
LineChart1.ChartTitle = string.Format("{0} and {1} Order Distribution", ddlPrice.SelectedItem.Value, ddlPrice2.SelectedItem.Value);
LineChart1.Visible = true;
}
private static DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["bwic testConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
date might be a reserved keyword, depending of the version you use. Write [date] instead. And this
"select price, date from Price where Price_type = '{0}' order by date)"
should be
"select price, date from Price where Price_type = '{0}' order by date"
You can try with this code
using (var con = new SqlConnection(constr))
{
using (var cmd = new SqlCommand(query))
{
using (var sda = new SqlDataAdapter())
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
There's nothing syntactically wrong with your GetData() method as shown in your original post. You might try commenting out the entire body of the method and then start uncommenting things one at a time to isolate the actual problem.
But it apparently seems that you don't have a syntax error: you have invalid SQL. The SQL you are trying to execute is:
select price, date from Price where Price_type = '{0}' order by date)
It has two things wrong with it:
The closing (right) parenthesis at the end is your syntax error, and
the parameter should not be enclosed in quotes.
Your SQL should look something like
select price, date from Price where Price_type = {0} order by date
Your method should look something like this:
private static DataTable GetData1( string query , string p0 )
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["bwic testConnectionString"].ConnectionString;
using ( SqlConnection con = new SqlConnection( constr ) )
using ( SqlCommand cmd = con.CreateCommand() )
using ( SqlDataAdapter sda = new SqlDataAdapter(cmd) )
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
SqlParameter p = new SqlParameter() ;
p.Value = p0Value ;
cmd.Parameters.Add( p ) ;
con.Open();
sda.Fill( dt );
con.Close();
}
return dt;
}
Don't forget to use brackets twice - in SELECT clause and in ORDER BY clause too.
in your code bolck as below
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
change it to
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
The problem here is that you havent opened any connection before filling.
You haven't opened a connection anywhere. You must open the connection before you can use it.
If your whole class code is really this, you are missing a closing } at the end of the file for the
public partial class Default2 : System.Web.UI.Page
{
declaration.

Categories

Resources