How to get the data of a specific column from an excel file? - asp.net

Hi I've an excel file which looks like this
id name age phne no and like this i have 35 columns.........
I'm using a webapplication for this in which I've a fileupload control,a button and two textboxes
fileuploadcontrol
button
textbox1
textbox2
Now when I upload the excel file on button click it should read complete file .........
and when I enter the required column in the textbox1 I get those column details only its like this
textbox1(c1,c4,c5,c30) I sholud get only those column details and in the other text box if I enter the location to be saved it should be saved in that location can any one help me with this I had finished till file uploading and reading.....all I need is how to evaluate those textboxes to get my required data
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentType == "application/xlsx")
{
path = Server.MapPath(".") + "\\inputfiles\\" + Guid.NewGuid() + FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(path);
Label1.Text = "File Uploaded Successfully...";
StreamReader reader = new StreamReader(FileUpload1.FileContent);
string text = reader.ReadToEnd();
}
else
Label1.Text = "Upload .xlsx File";
}
else
Label1.Text = "Upload file";
}

Check this:
Read and Display Data From an Excel File (.xsl or .xlsx) in ASP.NET
You can specify what columns you need to read on select query.
Regards

I got the answer myself .......ty for tryin to helpin me m postin my code if any needs in any case........
protected void btns_Click(object sender, EventArgs e)
{
string path = string.Empty;
location = Textbox2.Text;
if (fup1.HasFile)
{
try
{
path = Server.MapPath(".") + "\\uploadedfiles\\" + Guid.NewGuid() + fup1.FileName;
fup1.PostedFile.SaveAs(path);
lbl5.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
lbl5.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
excelfile(path);
}
}
void excelfile( string path)
{
string readfile = path;
// initialize the Excel Application class
Excel.Application app = new Excel.Application();
//Excel.Worksheet NwSheet;
Excel.Range ShtRange;
// create the workbook object by opening the excel file.
Excel.Workbook workBook = app.Workbooks.Open(readfile, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
// Get The Active Worksheet Using Sheet Name Or Active Sheet
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;
int index = 1;
System.Text.StringBuilder sb = new StringBuilder();
try
{
string[] values = Textbox1.Text.Split(new char[] { ',' });
int[] colindexs = new int[values.Length];
for (int i = 0; i < values.Length; i++)
{
colindexs[i] = Convert.ToInt16(values[i]);
}
while (((Excel.Range)workSheet.Cells[index, 1]).Value2 != null)
{
string str = "";
foreach (int col1 in colindexs)
{
str = str + Convert.ToString(((Excel.Range)workSheet.Cells[index, col1]).Value2) + ",";
}
str = str.Substring(0, str.Length - 1);
sb.Append(str);
sb.Append(Environment.NewLine);
index++;
}
Writetofile(sb.ToString());
ShtRange = workSheet.UsedRange;
}
catch (Exception ex)
{
app.Quit();
lbl5.Text=ex.Message;
}
}
void Writetofile(string content)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(location, true))
{
sw.Write(content);
sw.Flush();
}
}
}

Related

read from excel file to datatable asp.net

I got this code to read from a excel file after uploading
public static DataTable getDataTableFromExcel(string path)
{
using (var pck = new OfficeOpenXml.ExcelPackage())
{
using (var stream = File.OpenRead(path))
{
pck.Load(stream);
}
var ws = pck.Workbook.Worksheets.First();
DataTable tbl = new DataTable();
bool hasHeader = true; // adjust it accordingly( i've mentioned that this is a simple approach)
foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
{
tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
}
var startRow = hasHeader ? 2 : 1;
for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
{
var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
var row = tbl.NewRow();
foreach (var cell in wsRow)
{
row[cell.Start.Column - 1] = cell.Text;
}
tbl.Rows.Add(row);
}
return tbl;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/Uploader/") + filename);
err.Text = "Upload status: File uploaded!";
DataTable dt = getDataTableFromExcel(Server.MapPath("~/Uploader/") + filename);
GridView1.DataSource = dt;
GridView1.DataBind();
err.Text = dt.Rows[1].ToString();
}
catch (Exception ex)
{
err.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
but i cannot understand it well ... if you could give me a little description about it ?
and how to read specific column
I need to read just the first and third and fifth column not all ... how to do that ?

Error reading words in the text file

I have been working on a code snippet today . A part of the Code reads the number of words in the file.I am using StreamReader to do the same , but it seems to give DirectoryNotFound Exception.Here is the code for the event
protected void Button1_Click(object sender, EventArgs e)
{
string filename = string.Empty;
string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
if (FileUpload1.HasFile)
{
string[] Exe = { ".txt" };
string FileExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
bool isValidFile = Exe.Contains(FileExt);
if (isValidFile)
{
int FileSize = FileUpload1.PostedFile.ContentLength;
if (FileSize <= 102400)
{
filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath(FilePath) + filename);
StreamReader sr = new StreamReader(FilePath+filename);
//The error shows up here and i have tried to use FilePath as the single parameter too
int counter = 0;
string delim = " ,.?!";
string[] fields = null;
string line = null;
while (!sr.EndOfStream)
{
line = sr.ReadLine();//each time you read a line you should split it into the words
line.Trim();
fields = line.Split(delim.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
counter += fields.Length; //and just add how many of them there is
}
sr.Close();
lblcount.Text = counter.ToString();
lblMsg.Text = "File upload successfully!";
}
else
{
lblMsg.Text = "File Size allowed upto 100kb!";
}
}
else
{
lblMsg.Text = "Please Upload a text File!";
}
}
else
{
lblMsg.Text = "Please upload a file!";
}
}
}
Can this be sorted out ??
Thanks in Advance!
Use Path.Combine to build paths:
string path = Path.Combine(Server.MapPath(FilePath), filename);
FileUpload1.SaveAs(path);
using(StreamReader sr = new StreamReader(path))
{
// ...
}

asp.net upload control is not working in ipad

The asp.net upload control is uploading the file for first time in Ipad but not after that and not even showing any error
The code is as below
protected void UploadThisFile(FileUpload upload)
{
try
{
string folderpath = ConfigurationManager.AppSettings["BTCommDynamic"].ToString() + ConfigurationManager.AppSettings["Attachments"].ToString();
Guid fileguid = Guid.NewGuid();
string filename = fileguid + upload.FileName;
if (upload.HasFile && dtFiles != null)
{
DataRow drFileRow = dtFiles.NewRow();
drFileRow["FileName"] = upload.FileName;
string theFileName = Path.Combine(Server.MapPath(folderpath), filename);
string theFileName1 = Path.Combine(folderpath, filename);
//string theFileName = folderpath;
//to save the file in specified path
upload.SaveAs(theFileName);
drFileRow["FilePath"] = theFileName1;
double Filesize = (upload.FileContent.Length);
if (Filesize > 1024)
{
drFileRow["FileSize"] = (upload.FileContent.Length / 1024).ToString() + " KB";
}
else
{
drFileRow["FileSize"] = (upload.FileContent.Length).ToString() + " Bytes";
}
dtFiles.Rows.Add(drFileRow);
gvAttachment.DataSource = dtFiles;
gvAttachment.DataBind();
}
}
catch (Exception ex)
{
string message = Utility.GetExceptionMessage(ex.GetType().ToString(), ex.Message);
Display_Message(message);
}
}
Do you use firebug? There might be an error on a client side that prevents the work of your functionality.
Do you have any logic on your client side? Some kinda jquery/ajax calls?

Bind two datasources into one grid

I have two input controls through which I need to browse and upload the documents.
Below is my ascx
I need to have both teh files uploaded in the gridview.
Below is the code on how I am trying to achieve this.I am creating a datatable for the first upload and then a second datatable for the second upload, and then merging the twodatables into a new combined one and assigning that as the datasource for the gridview.
namespace Sharepoint.WebParts.Upload_WebPart
{
public partial class Upload_WebPartUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
this.btnUpload.Click += new EventHandler(btnUploadUploadClick);
this.uploadsupport.Click+=new EventHandler(uploadsupport_Click);
this.btnSubmit.Click += new EventHandler(btnSubmit_Click);
this.dgdUpload.RowDeleting += new GridViewDeleteEventHandler(dgdUpload_RowDeleting);
}
protected void btnUploadUploadClick(object sender, EventArgs e)
{
fileName = System.IO.Path.GetFileName(inputFile.PostedFile.FileName);
string x = Path.GetExtension(fileName);
if (fileName != "")
{
if (x == ".zip")
{
string _fileTime = DateTime.Now.ToFileTime().ToString();
string _fileorgPath = System.IO.Path.GetFullPath(inputFile.PostedFile.FileName);
string _newfilePath = _fileTime + "~" + fileName;
length = (inputFile.PostedFile.InputStream.Length) / 1024;
string tempFolder = Environment.GetEnvironmentVariable("TEMP");
string _filepath = tempFolder + _newfilePath;
inputFile.PostedFile.SaveAs(_filepath);
AddRow(fileName, _filepath, length);
lblMessage.Text = "Successfully Added in List";
}
else
{
lblMessage.Text = "Please upload a zip file";
return;
}
}
else
{
lblMessage.Text = "Select a File";
return;
}
}
private void AddMoreColumns()
{
dt = new DataTable("DT");
dc = new DataColumn("FileName", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("FilePath", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("FileSize", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("KB", Type.GetType("System.String"));
dt.Columns.Add(dc);
Page.Session["DT"] = dt;
}
private void AddRow(string file, string path, double length)
{
dt = (DataTable)Page.Session["DT"];
if (dt == null)
{
AddMoreColumns();
}
dr = dt.NewRow();
dr["FileName"] = file;
dr["FilePath"] = path;
dr["FileSize"] = Convert.ToString(length);
dr["KB"] = "KB";
dt.Rows.Add(dr);
Page.Session["DT"] = dt;
}
Similary i add rows to the datatable dt1.
protected void bindgridview()
{
dt = (DataTable)Page.Session["DT"];
dt1 = (DataTable)Page.Session["DT1"];
joineddt = (DataTable)Page.Session["Files"];
if (joineddt == null)
{
joineddt = dt.Copy();
joineddt.Merge(dt1);
}
this.dgdUpload.DataSource = joineddt;
this.dgdUpload.DataBind();
Page.Session["Files"] = joineddt;
}}
}
Please help me to correct this , also is there a simple way to achieve this.
You can't databind to more than one data source at the same time. If the datatable joineddt does not have SupportName in it then your code would not work.
Rather than trying to try an finagle 2 data sources into one GridView, you should create one data source that has all the data you expect to display in a row of the GridView in one row of the data source.

How to change fileupload name

im using following code to upload
protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~upload/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
I want to change the upload file name...I have to assign file name for every uploaded file how?
This line pickes up the the name of the uploaded file:
string filename = Path.GetFileName(FileUploadControl.FileName);
This line tells the server what to save the file as:
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
Simply change the value of filename to something else before saving.
there is a way to change the name of the file that we downloaded to our "~Server/Userfolder"(as an example)..
i was really thinking on renaming file before the .SaveAs command, which is gonna be like:
if (Request.Files != null)
{
var getmyfile = Request.Files["some_photo"];
try
{
if (getmyfile.FileName != "" && getmyfile.FileName != null && getmyfile.ContentLength > 0)
{
///Create Useruploads path.
var path = Server.MapPath("~/Useruploads" + "\\");
///Get file info that we gonna upload to server..
FileInfo TheFile = new FileInfo(path + Path.GetFileName(getmyfile.FileName));
///Note: i used Path.GetFileName(getmyfile.FileName) code cause getmyfile.FileName gives full path of that file..
if (TheFile.Exists)
{
///Seperate file name and extention..
var fname = Path.GetFileNameWithoutExtension(TheFile.Name);
var ext = TheFile.Extension;
var path2 = path + fname;
///As long as we got file names, same as in server..
while(new FileInfo(path2+ext).Exists)
{
///Add "-img" to its name..
path2 = path2 + "-img";
}
FileInfo ccc = new FileInfo(path2 + ext);
string f_art = ccc.Name.Replace(" ", "");///Clean space.. (Optional)
getmyfile.SaveAs(f_art);
somedb.some_photo = Path.GetFileName(f_art); ///Its not fart its file art lol!
}
else ///if file is not exist in our server..
{
var path3 = (path + Path.GetFileName(getmyfile.FileName));
FileInfo ccc = new FileInfo(path3);
string f_art = ccc.Name.Replace(" ", "");
getmyfile.SaveAs(f_art);
some.some_photo = Path.GetFileName(f_art);
}
}
}
catch(FileNotFoundException ex)
{
form.Set("lblStatus",ex.Message);
}
catch (Exception ex)
{
form.Set("lblStatus", ex.Message);
}
db.somedbs.InsertOnSubmit(somedb);
db.SubmitChanges();
return RedirectToAction("Index");
}
(Optional) Also u can use :
var f_art = System.Text.RegularExpressions.Regex.Replace(Path.GetFileNameWithoutExtension(TheFile.Name), "[^a-zA-Z]", "");
instead of using .Replace(" ",""); but at this it just cleans spaced areas and if u use the code up there its gonna clean everything except A to Z , a to z characters which means no numbers will be applied to that name nor space or other characters which are not between A and Z..

Resources