Import CSV file into Grid View in Asp.net - asp.net

How to load the CSV file dynamically inside Grid View in C# Asp.net without hard coded values?

if (File.Exists(myFileUpload.PostedFile.FileName))
{
string[] data = File.ReadAllLines(myFileUpload.PostedFile.FileName);
DataTable dt = new DataTable();
string[] col = data[0].Split(',');
foreach (string s in col)
{
dt.Columns.Add(s, typeof(string));
}
for (int i = 0; i < data.Length; i++)
{
string[] row = data[i].Split(',');
dt.Rows.Add(row);
}
myGridView.DataSource = dt;
myGridView.DataBind();
}

Related

Open XML generates only <NewDataSet /> tag from a full Excel file, but work for other files

I have an excel file full of data, and I'm trying to use Open XML SDK to convert this file into xml file.
I followed the documentation and other questions here on stackoverflow. However, the output of the xml file is always <NewDataSet />. Knowing that I tried other excel files and it worked fine.
Here is how my excel file looks like:
And here is my code "I tried two approaches":
The first approach is to use DataSet.GetXML(), it returned the same value as the next code does.
var xmlDS = new ConvertExcelToXml().GetXML(filePath);
string xmlPath = server.MapPath("~/UploadedFiles/XML/");
StreamWriter xmlFile = new StreamWriter(xmlPath + Path.GetFileNameWithoutExtension(fileName) + ".xml");
xmlDS.WriteXml(xmlFile);
//The used method to return the excel file dataset
public DataSet GetXML(string filename)
{
using (DataSet ds = new DataSet())
{
ds.Tables.Add(this.ReadExcelFile(filename));
return ds;
}
}
//This method used to return DataTable for previous method
private DataTable ReadExcelFile(string filename)
{
DataTable dt = new DataTable();
try
{
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, false))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
IEnumerable<Sheet> sheetcollection = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
string relationshipId = sheetcollection.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(relationshipId);
SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
IEnumerable<Row> rowcollection = sheetData.Descendants<Row>();
if (rowcollection.Count() == 0)
{
return dt;
}
foreach (Cell cell in rowcollection.ElementAt(0))
{
dt.Columns.Add(GetValueOfCell(spreadsheetDocument, cell));
}
foreach (Row row in rowcollection)
{
DataRow temprow = dt.NewRow();
int columnIndex = 0;
foreach (Cell cell in row.Descendants<Cell>())
{
int cellColumnIndex = GetColumnIndex(GetColumnName(cell.CellReference));
if (columnIndex < cellColumnIndex)
{
do
{
temprow[columnIndex] = string.Empty;
columnIndex++;
}
while (columnIndex < cellColumnIndex);
}
temprow[columnIndex] = GetValueOfCell(spreadsheetDocument, cell);
columnIndex++;
}
dt.Rows.Add(temprow);
}
}
dt.Rows.RemoveAt(0);
return dt;
}
catch (IOException ex)
{
throw new IOException(ex.Message);
}
}

Adding Fields to DataTable in ASP.net MVC

Users are uploading an Excel file to my site which I'm then going to write to the database. I'd like to add two additional columns (Email and TimeStamp). I'm not getting any specific error. Any suggestions on how to remedy? Code below:
public static class ExcelPackageExtensions
{
public static DataTable ToDataTable(this ExcelPackage package)
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.First();
DataTable dt = new DataTable();
dt.Columns.Add("Email");
dt.Columns.Add("TimeStamp");
foreach (var firstRowCell in worksheet.Cells[1,1,1,worksheet.Dimension.End.Column])
{
dt.Columns.Add(firstRowCell.Text);
}
for (var rownumber=2; rownumber <= worksheet.Dimension.End.Row; rownumber++)
{
var row = worksheet.Cells[rownumber, 1, rownumber, worksheet.Dimension.End.Column];
var newrow = dt.NewRow();
newrow["Email"] = System.Web.HttpContext.Current.User.Identity.GetUserId();
newrow["TimeStamp"] = DateTime.Now;
foreach (var cell in row)
{
newrow[cell.Start.Column - 1] = cell.Text;
}
dt.Rows.Add(newrow);
}
return dt;
}
}

Exporting a grid view to datatable

How can i export a .net GridView into a DataTable.
I am not setting any data source to the GridView all data are entered by user...
If any body knows please help me..thanks in advance....
The Following Code will help you in adding the Gridview rows to DataTable
DataTable dt = new DataTable();
for (int j = 0; j < grdList.Rows.Count; j++)
{
DataRow dr;
GridViewRow row = grdList.Rows[j];
dr = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dr[i] = row.Cells[i].Text;
}
dt.Rows.Add(dr);
}

How can i bind a table from oracle directly to pdf

How can I bind data from oracle database to pdf in asp.net 4.0?
I don't know if this is possible directly. You might take a look at iTextSharp for generating PDF files in .NET.
Did you try using PL/PDF ? Haven't used it personally, but its the only direct method of creating/populating PDFs out of Oracle that I know of (unless perhaps Apex has some plug-in)
Thank you soo much for your responses. I got the answer. Below is the code for binding a database table from an Oracle database to PDF in ASP.net
using System.Web.UI.WebControls;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Data;
public partial class generate_pdf_from_dataset : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection("User id=book;Password=book;Data Source=test");
OracleDataAdapter da = new OracleDataAdapter("select * from category" , con);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
Document pdfDoc = new Document(PageSize.A4, 30, 30, 40, 25);
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
int cols = dt.Columns.Count;
int rows = dt.Rows.Count;
pdfDoc.Open();
iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
pdfTable.BorderWidth = 1;
pdfTable.Width = 100;
pdfTable.Padding = 1;
pdfTable.Spacing = 1;
//creating table headers
for (int i = 0; i < cols; i++)
{
Cell cellCols = new Cell();
Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 12, Font.BOLD);
Chunk chunkCols = new Chunk(dt.Columns[i].ColumnName, ColFont);
cellCols.Add(chunkCols);
pdfTable.AddCell(cellCols);
}
//creating table data (actual result)
for (int k = 0; k < rows; k++)
{
for (int j = 0; j < cols; j++)
{
Cell cellRows = new Cell();
Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
Chunk chunkRows = new Chunk(dt.Rows[k][j].ToString(), RowFont);
cellRows.Add(chunkRows);
pdfTable.AddCell(cellRows);
}
}
pdfDoc.Add(pdfTable);
pdfDoc.Close();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf");
Response.Clear();
Response.BinaryWrite(mStream.ToArray());
Response.End();
}
}

Dynamically create Asp Chart multi series

How to create multi series ASP.net chart dynamically.
private void BindChart(DataTable dt)
{
dt.DefaultView.Sort = "Category Asc";
DataTable dtSorted = dt.DefaultView.ToTable();
string sCategoryName = string.Empty;
string sOldCategoryName = string.Empty;
for (int i = 0; i < dtSorted.Rows.Count; i++)
{
sCategoryName = dtSorted.Rows[i]["Category"].ToString();
if (sCategoryName != sOldCategoryName)
{
// Your logic here to bind the category in chart
sOldCategoryName = sCategoryName;
}
// Bind other details (description etc) from the table.
}
}

Resources