Get all the values from excel file by using linqtoexcel - c#

I'm using linqtoexcel in my asp.net mvc 4 project to read an excel file & get all the values from there. But I'm only getting the values of last row. Here are my codes,
Controller
public ActionResult ExcelRead()
{
string pathToExcelFile = ""
+ #"C:\MyFolder\ProjectFolder\sample.xlsx";
string sheetName = "Sheet1";
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var getData = from a in excelFile.Worksheet(sheetName) select a;
foreach (var a in getData)
{
string getInfo = "Name: "+ a["Name"] +"; Amount: "+ a["Amount"] +">> ";
ViewBag.excelRead = getInfo;
}
return View();
}
View
#ViewBag.excelRead
How can I get the values from all the rows? Need this help badly! Thanks.

Try this (expanding on #Sachu's comment to the question) -
public ActionResult ExcelRead()
{
string pathToExcelFile = ""
+ #"C:\MyFolder\ProjectFolder\sample.xlsx";
string sheetName = "Sheet1";
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var getData = from a in excelFile.Worksheet(sheetName) select a;
string getInfo = String.Empty;
foreach (var a in getData)
{
getInfo += "Name: "+ a["Name"] +"; Amount: "+ a["Amount"] +">> ";
}
ViewBag.excelRead = getInfo;
return View();
}

Make the getDate as .ToList()
var getData = (from a in excelFile.Worksheet(sheetName) select a);
List<string> getInfo = new List<string>();
foreach (var a in getData)
{
getInfo.Add("Name: "+ a["Name"] +"; Amount: "+ a["Amount"] +">> ");
}
ViewBag.excelRead = getInfo;
return View();
Then pass this to the view
and do a foreach loop with #ViewBag.excelRead
foreach (var data in #ViewBag.excelRead)
{
.....
}
Hope this helps

Related

c# - How to call/link a workflow on a web application from a c# program?

I have a C# (WinForms) application that can scan documents via a printer. After scanning, I will be able to enter document details on it and have a button to finalize the documents. The documents details and info will be stored in my database ABC in certain tables.
Now, I have another web application written in Java(IntelliJ) that has some button functionality to upload documents and then start a workflow and route it to another user to approve the document. I won't go into detail on the specifics. This application also connects to the same database ABC.
So now comes the tougher part, I need to link these two applications in a way that when I finalize my document
on the C# application, it has to auto trigger the workflow on the web application side. Rather than manually starting the workflow on the web application, it would just call or trigger the workflow, so I do not need to access the web application at all for the process to start.
private void FinButton_Click(object sender, EventArgs e)
{
int count = 0;
var txtBoxFields = new List<TextBox>
{
textBox1,
textBox2,
textBox3,
textBox4,
textBox5,
textBox6,
textBox7,
textBox8,
textBox9,
textBox10,
textBox11,
textBox12,
textBox13,
textBox14,
textBox15
};
var templateFields = new List<String>
{
"T1",
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15"
};
//long tid = 0;
//Start insert query into templatebatch table in db
var dbConnection2 = DBConnection.Instance();
dbConnection2.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection2.IsConnect())
{
bool test = true;
for (int i = 1; i <= 15; i++)
{
var input = txtBoxFields[i - 1].Text;
var insertQuery = "INSERT INTO templateinfo(TID, THEADER, " + templateFields[i - 1] + ") VALUES(#tid, #theader,#t" + i + ")";
var insertCmd = new MySqlCommand(insertQuery, dbConnection2.Connection);
insertCmd.Parameters.AddWithValue("#tid", tid);
insertCmd.Parameters.AddWithValue("#theader", "N");
if (String.IsNullOrEmpty(input))
{
count = 1;
insertCmd.Parameters.AddWithValue("#t" + i, String.Empty);
break;
}
else
{
if (test)
{
insertCmd.Parameters.AddWithValue("#t" + i, txtBoxFields[i - 1].Text);
insertCmd.ExecuteNonQuery();
test = false;
var selectQuery = "select TINFOID from templateinfo where TID=" + tid + " and THEADER = 'N'";
var selectCmd = new MySqlCommand(selectQuery, dbConnection2.Connection);
var selectReader = selectCmd.ExecuteReader();
using (MySqlDataReader dr = selectReader)
{
while (dr.Read())
{
tinfoid = Convert.ToInt32(dr["TINFOID"]);
}
}
}
else
{
var updateQuery = "update templateinfo set " + templateFields[i - 1] + "='" + txtBoxFields[i - 1].Text + "' where TINFOID = '" + tinfoid + "' and TID=" + tid + " and THEADER='N'";
var updateCmd = new MySqlCommand(updateQuery, dbConnection2.Connection);
var updateReader = updateCmd.ExecuteReader();
using (var reader = updateReader)
{
}
}
}
}
}
if (count == 1)
{
//MessageBox.Show("Input field(s) cannot be left empty.");
}
//Finalize here
var client = new LTATImagingServiceClient();
client.Finalize(userID, tid, tinfoid, batchID);
Debug.WriteLine(userID + ", " + tid + ", " + tinfoid + ", " + batchID);
var batchName = templateView.SelectedNode.Text;
var folderPath = #"C:\temp\batches\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
ThumbnailLists.Items.Clear();
// var img = Image.FromFile(#"C:\temp\batch-done.png");
if (ImageBox.Image != null)
{
ImageBox.Image.Dispose();
}
ImageBox.Image = null;
try
{
using (new Impersonation(_remoteDomain, _remoteUser, _remotePassword))
{
// MessageBox.Show(_remoteUser);
// MessageBox.Show(_remotePassword);
var tPath = #"\\126.32.3.178\PantonSys\SAM\Storage\3\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
bool exists = System.IO.Directory.Exists(tPath);
if (!exists)
{
System.IO.Directory.CreateDirectory(tPath);
}
string[] fileList = Directory.GetFiles(folderPath, "*");
foreach (var file in fileList)
{
File.Copy(file, tPath + Path.GetFileName(file));
}
CurrentPageBox.Text = "";
NumberPageBox.Text = "";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
var dbConnection = DBConnection.Instance();
dbConnection.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection.IsConnect())
{
var deleteBatchQuery = "DELETE FROM templatebatch WHERE batchname ='" + templateView.SelectedNode.Text + "'";
var deleteBatchCmd = new MySqlCommand(deleteBatchQuery, dbConnection.Connection);
var deleteBatchReader = deleteBatchCmd.ExecuteReader();
using (var reader = deleteBatchReader)
{
while (reader.Read())
{
}
}
templateView.Nodes.Remove(templateView.SelectedNode);
Directory.Delete(folderPath, true);
MessageBox.Show("Successfully Transferred.");
foreach (var txtFields in txtBoxFields)
{
txtFields.Text = "";
txtFields.Enabled = false;
}
finButton.Visible = false;
finButton.Enabled = false;
}
bindButton.Visible = false;
}
Would this be possible to achieve or just being far-fetched?
I would appreciate any suggestions or pointers on this. Do let me know if there is anything unclear in my explanation.
EDIT:
Request URL: http://126.32.3.178:8111/process/taskmanager/start/start.jsp
Request Method: POST
Status Code: 200 OK
Remote Address: 126.32.3.178:8111
Referrer Policy: no-referrer-when-downgrade
Is there a way I could call this from the C# application?
You can send your file directly from your C# app with use of Http client. Here is code sample:
private async Task<bool> Upload(string filePath)
{
const string actionUrl = #"http://126.32.3.178:8111/process/taskmanager/start/start.jsp";
var fileName = Path.GetFileName(filePath);
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, fileName);
var response = await client.PostAsync(actionUrl, formData);
return response.IsSuccessStatusCode;
}
}
Also, note that there maybe some sort of authentication should be performed before you can post a request.

how not to overwrite in FileUpload in C#

in the code below
public class UploadController : ApiController
{
[HttpPost]
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/Files/" + postedFile.FileName);
postedFile.SaveAs(filePath);
var fileName = postedFile.FileName;
var extension = Path.GetExtension(fileName);
var nameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
var i = 1;
while (File.Exists(filePath + fileName))
{
fileName = nameWithoutExtension.Trim() + " (" + i + ")" + extension;
i++;
}
docfiles.Add(filePath + fileName);
// docfiles.Add(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
}
I really want to make a file upload the classic filename(1).jpg if file name is already exists but the code I had still delete the old files that has the same name, I don't know where I got it wrong i used while loop but it wasnt working
I tried fixing it the code below is working now it turns out i constructed it wrong :)
var filePath = HttpContext.Current.Server.MapPath("~/Files/" );
var postedFile = httpRequest.Files[file];
var fileName = postedFile.FileName;
var extension = Path.GetExtension(fileName);
var nameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
var i = 1;
while (File.Exists(filePath + fileName))
{
fileName = nameWithoutExtension.Trim() + " (" + i + ")" + extension;
i++;
}
postedFile.SaveAs(filePath + fileName);

Why my code can't locate the data table?

I have this code below to generate a report. My problem is why one of the content of my data table can't locate by my code? The ds.dt_ProposedSeminars is the table.
public JsonResult ReportProposal(int year)
{
string Userkey = "gHeOai6bFzWskyUxX2ivq4+pJ7ALwbzwF55dZvy/23BrHAfvDVj7mg ";
string PassKey = "lLAHwegN8zdS7mIZyZZj+EmzlkUXkvEYxLvgAYjuBVtU8sw6wKXy2g ";
JsonResult result = new JsonResult();
MemoryStream oStream;
PCSO_ProposedSeminars rpt = new PCSO_ProposedSeminars();
dsPCSO_TrainingProgram ds = new dsPCSO_TrainingProgram();
//-----------------------------------------------------
var seminars = db.Certificates
.Where(x => x.Year.Value.Year == year && !x.IsApproved.HasValue)
.Select(z => z).Distinct();
foreach (var train in seminars)
{
string trainingProgram = train.CertificateName;
string resourcePerson = train.ResourceSpeaker;
string target = "";
var classifications = db.CertificateTrainingClassifications.Where(a => a.CertificateId == train.CertificateId).Select(b=>b.TrainingClassification.Classification);
int x = 1;
foreach (var classification in classifications)
{
if (classifications.Count() > 1)
{
if (x == 1) target += classification;
else target += ", " + classification;
}
else target += classification;
x++;
}
if (train.TargetParticipants.HasValue)
{
target += "/" + train.TargetParticipants.Value + ((train.TargetParticipants != null) ? " pax" : "");
}
if (train.IsPerBatch.Value)
{
target += "/batch";
}
string duration = train.Duration.Value + " days";
decimal estimatedExpenses = new decimal();
estimatedExpenses = train.EstimatedExpenses.Value;
ds.dt_ProposedSeminars.Adddt_ProposedSeminarsRow(
trainingProgram,
resourcePerson,
target,
duration,
estimatedExpenses);
}
DataTable dtable = new DataTable();
dtable = ds.dt_ProposedSeminars;
rpt.SetDataSource(dtable);
rpt.Refresh();
rpt.SetParameterValue(0, year);
rpt.SetParameterValue(1, "");
rpt.SetParameterValue(2, "Head, Training Unit, Admin Department");
oStream = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
string filename = Convert.ToString((DateTime.Now.Month) + Convert.ToString(DateTime.Now.Day) + Convert.ToString(DateTime.Now.Year) + Convert.ToString(DateTime.Now.Hour) + Convert.ToString(DateTime.Now.Minute) + Convert.ToString(DateTime.Now.Second) + Convert.ToString(DateTime.Now.Millisecond)) + "RequestApplication";
var len = oStream.Length;
FileTransferServiceClient client2 = new FileTransferServiceClient();
RemoteFileInfo rmi = new RemoteFileInfo();
DateTime dt = DateTime.Now;
DownloadRequest dr = new DownloadRequest();
string fId = client2.UploadFileGetId("", filename, len, PassKey, Userkey, oStream);
result.Data = new
{
fileId = fId,
filename = filename
};
rpt.Close();
rpt.Dispose();
oStream.Close();
oStream.Dispose();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
}
Here is the screenshot:
Here is the error.
'PIMS_Reports.TrainingProgram.dsPCSO_TrainingProgram' does not contain a definition for 'dt_ProposedSeminars' and no extension method 'dt_ProposedSeminars' accepting a first arguement of type
'PIMS_Reports.TrainingProgram.dsPCSO_TrainingProgram' could not be found (are you missing a using directive assembly reference?)
The error message states that your dsPCSO_TrainingProgram class does not contain a method or property named dt_PropsedSeminars.
What does that class look like?

put data from simpleDB into data gridview

I was trying to retrieve data from Amazon SimpleDB and currently it only displays data in text like domainName: {attribute1, value2} {attribute1, value2}.
How can I show the data in data grid view? My code is as follows:
public static List<String> GetItemByQuery(IAmazonSimpleDB simpleDBClient, string domainName)
{
List<String> Results = new List<String>(); ;
SelectResponse response = simpleDBClient.Select(new SelectRequest()
{
SelectExpression = "Select * from " + domainName
});
String res = domainName + " has: ";
foreach (Item item in response.Items)
{
res = item.Name + ": ";
foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attributes)
{
res += "{" + attribute.Name + ", " + attribute.Value + "}, ";
}
res = res.Remove(res.Length - 2);
Results.Add(res);
}
return Results;
}
How you an read here:
http://docs.aws.amazon.com/sdkfornet1/latest/apidocs/html/P_Amazon_SimpleDB_Model_SelectResult_Item.htm
your response.Items is
public List<Item> Item { get; set; }
so you should directly use to DataSource of your Grid, set autogenerate column to your grid to start to view the result

Mvc : displaying a List<student> from the database in a text file with click of button

I am new to mvc. I have a controller with two methods. I want to return a list to a text
file on the click of a button. I have been trying to figure out a way how I can pass
the list to the CreateReportFile method but no luck. It works very well for stringbuilder objects.
Do you have an idea of how I can display the List in a text file?
#Html.ActionLink("Download File", "CreateReportFile");
public FileStreamResult CreateReportFile()
{
//todo: add some data from your database into that string:
var string_with_your_data = string.Empty;
var byteArray = Encoding.ASCII.GetBytes(string_with_your_data);
var stream = new MemoryStream(byteArray);
return File(stream, "text/plain", "Report" + DateTime.Now + ".txt");
}
public List<Student> GetStudents()
{
return new List<Student>()
{
new Student() {firstname="james",lastname="john",emailAddress="james.john#yahoo.com"},
new Student() {firstname="patric",lastname="swayze",emailAddress="patric.swayze#yahoo.com"},
new Student() {firstname="james",lastname="john",emailAddress="james.john#yahoo.com"},
new Student() {firstname="toy",lastname="gas",emailAddress="toy.gas#yahoo.com"}
};
}
If you are trying to get the students list into that string you are writing to the file you could try:
public FileStreamResult CreateReportFile()
{
List<Student> students = GetStudents();
StringBuilder sb = new StringBuilder();
foreach (Student s in students)
sb.AppendLine(s.firstname + ", " + s.lastname + ", " + s.emailAddress);
var string_with_your_data = sb.ToString();
var byteArray = Encoding.ASCII.GetBytes(string_with_your_data);
var stream = new MemoryStream(byteArray);
return File(stream, "text/plain", "Report" + DateTime.Now + ".txt");
}
All you should have to do is add this to make it a string and then send the data.
foreach(Student test in GetStudents())
{
string_with_your_data += test.firstname + ", " + test.lastname + ", " + test.emailAddress + "\r\n";
}
If you're asking how to convert List object into text you will need to create a method that does that OR you can use a Serializer, but that will format it into json or xml.
To convert the object yourself in your student object you can override ToString with something like this:
public override string ToString()
{
return String.Format("firstname={0}, lastname={1}, emailAddress={2}", firstname, lastname, emailAddress);
}
Then you can loop through your list
string mystring = string.Empty;
foreach(var student in Students)
mystring += student.ToString() + "\n";
Just some ideas that might get you started.

Categories