Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
My application needs to read data from an excel file and stocks it in MongoDB database. I am using .Net and c# for development.I am using Excel 2007 , MongoDB 3.2 and visual studio 2015 version.
Any idea to access excel file, i need your help please.
This is my code
public void Open_readXLS()
{
Excel.Workbook workbook;
Excel.Worksheet worksheet;
Optioncontext ctx = new Optioncontext();
string filePath = #"C:\Users\user PC\Desktop\ finale\Euro_Dollar_Call_Options.xlsx";
workbook = new Excel.Workbook(filePath);
worksheet = workbook.Sheets.GetByName("Feuil1");
for (ushort i = 0; i <= worksheet.Rows.LastRow; i++)
{
option.type_option= worksheet.Rows[i].Cells[0].Value.ToString(),
option.type_currency= worksheet.Rows[i].Cells[1].Value.ToString();
}
ctx.Option.InsertOne(option);
}
There are many ways of achieving this. The simplest would be to save your Excel as a CSV-file for further processing; you can do this in Excel by selecting "Save As" in the "File" menu and then changing the file-ending to CSV. Once you have done this you can use mongoimport to import its contents - no need for C# code in this scenario. You may have to adjust the contents of your CSV so that it fits the structure that is expected by mongoimport; here is a SO post about just that How to use mongoimport to import csv.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I wonder how we can read an excel file from C# code in a Mac.
Generally we cannot use Microsoft Excel in MAC. I tried to do it by converting the Excel into a .csv and then read the same.
Is there any alternate for this? Any better approach will help
Thanks in advance
I think, you can use the ExcelDataReader library
It's a cross-platform library.
Short sample from github:
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}
//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying to Convert a MVC 4 View to a PDF. I have no idea where to start, after searching google i found ItextSharp and have been playing around with it.
My View is fairly Simple it has a Map and a Table. i would like to just call an action in the controller and have it print my web page.
Any Advice would be greatly Appreciated
You can use Rotativa
public ActionResult TestViewWithModel(string id)
{
var model = new TestViewModel {DocTitle = id, DocContent = "This is a test"};
return new ViewAsPdf(model);
}
public ActionResult PrintIndex()
{
return new ActionAsPdf("Index", new { name = "Giorgio" }) { FileName = "Test.pdf" };
}
It uses wkhtmltopdf under the hood.
wkhtmltopdf and wkhtmltoimage are open source (LGPLv3) command line
tools to render HTML into PDF and various image formats using the QT
Webkit rendering engine. These run entirely "headless" and do not
require a display or display service.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have the following situation:
A document view where user can upload multiple files. A one(Document) to many(files) relationship. All these files are "inside" the document by its IDDocument property.
The user will make loads of .xml files upload, each file upload fires that Action in my controller:
[HttpPost]
public ActionResult ProcessSubmitUpload(HttpPostedFileBase attachments, Guid? idDocument)
{
//Validations
var xmlDocument = XDocument.Load(attachments.InputStream);
if (xmlDocument.Root.Name.LocalName == "cteProc")
{
if (DocumentCommonHelper.SendXmlViaWebService(xmlDocument))
{
_documentRepository.UpdateDocumentStatus(StatusOption.DocumentApproved);
}
else
{
_documentRepository.UpdateDocumentStatus(StatusOption.DocumentPending);
}
}
}
The logic is: If all files go correctly in the DocumentCommonHelper.SendXmlViaWebService(xmlDocument) , the document status must be Approved. But if one single file fails, the document status must be Pending.
The problem is that approach in this code is wrong. Because its changing the status of the document each time that the Action is executed, forgeting the others HttpPostedFileBase that are passed before.
What is the best way to do that?
Try to store the HttpPostedFileBase in the Session and retrieve them back when you need it
Session["HttpPostedFileBase"] = attachments;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
I am trying to save a PDF file by saving the data from the FDF into a PDFTemplate, in my WPF application.
So, the situation is like this. I have a PDFTemplate.pdf which serves as a template and has placeholders (or fields). Now I generate this FDF file pro-grammatically, which in turn contain all the field names required for the PDFTemplate to be filled in. Also, this FDF contains the file path for the PDFTemaplte also, so that on opening, it knows which PDF to use.
Now, when try and double click on the FDF, it open the Adober Acrobat Reader and displays the PDFTemplate with the data filled in. But I can't save this file using the File menu, as it says this file will be saved without the data.
I would like to know if it is possible to import the FDF data into PDF and save it without using a thrid party component.
Also, if it is very difficult to do this, what would be the possible solution in terms of a free library that would be able to do it?
I just realized that iTextSharp is not free for commercial applications.
I have been able to achieve this using another library PDFSharp.
It is somewhat similar to how iTextSharp works except for some places where in iTextSharp is better and easier to use. I am posting the code in case someone would want to do something similar:
//Create a copy of the original PDF file from source
//to the destination location
File.Copy(formLocation, outputFileNameAndPath, true);
//Open the newly created PDF file
using (var pdfDoc = PdfSharp.Pdf.IO.PdfReader.Open(
outputFileNameAndPath,
PdfSharp.Pdf.IO.PdfDocumentOpenMode.Modify))
{
//Get the fields from the PDF into which the data
//is supposed to be inserted
var pdfFields = pdfDoc.AcroForm.Fields;
//To allow appearance of the fields
if (pdfDoc.AcroForm.Elements.ContainsKey("/NeedAppearances") == false)
{
pdfDoc.AcroForm.Elements.Add(
"/NeedAppearances",
new PdfSharp.Pdf.PdfBoolean(true));
}
else
{
pdfDoc.AcroForm.Elements["/NeedAppearances"] =
new PdfSharp.Pdf.PdfBoolean(true);
}
//To set the readonly flags for fields to their original values
bool flag = false;
//Iterate through the fields from PDF
for (int i = 0; i < pdfFields.Count(); i++)
{
try
{
//Get the current PDF field
var pdfField = pdfFields[i];
flag = pdfField.ReadOnly;
//Check if it is readonly and make it false
if (pdfField.ReadOnly)
{
pdfField.ReadOnly = false;
}
pdfField.Value = new PdfSharp.Pdf.PdfString(
fdfDataDictionary.Where(
p => p.Key == pdfField.Name)
.FirstOrDefault().Value);
//Set the Readonly flag back to the field
pdfField.ReadOnly = flag;
}
catch (Exception ex)
{
throw new Exception(ERROR_FILE_WRITE_FAILURE + ex.Message);
}
}
//Save the PDF to the output destination
pdfDoc.Save(outputFileNameAndPath);
pdfDoc.Close();
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I need to determine the number of pages in a specified PDF file using C# code (.NET 2.0). The PDF file will be read from the file system, and not from an URL. Does anyone have any idea on how this could be done? Note: Adobe Acrobat Reader is installed on the PC where this check will be carried out.
You'll need a PDF API for C#. iTextSharp is one possible API, though better ones might exist.
iTextSharp Example
You must install iTextSharp.dll as a reference. Download iTextsharp from SourceForge.net This is a complete working program using a console application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
namespace GetPages_PDF
{
class Program
{
static void Main(string[] args)
{
// Right side of equation is location of YOUR pdf file
string ppath = "C:\\aworking\\Hawkins.pdf";
PdfReader pdfReader = new PdfReader(ppath);
int numberOfPages = pdfReader.NumberOfPages;
Console.WriteLine(numberOfPages);
Console.ReadLine();
}
}
}
This should do the trick:
public int getNumberOfPdfPages(string fileName)
{
using (StreamReader sr = new StreamReader(File.OpenRead(fileName)))
{
Regex regex = new Regex(#"/Type\s*/Page[^s]");
MatchCollection matches = regex.Matches(sr.ReadToEnd());
return matches.Count;
}
}
From Rachael's answer and this one too.
found a way at http://www.dotnetspider.com/resources/21866-Count-pages-PDF-file.aspx
this does not require purchase of a pdf library
One Line:
int pdfPageCount = System.IO.File.ReadAllText("example.pdf").Split(new string[] { "/Type /Page" }, StringSplitOptions.None).Count()-2;
Recommended:
ITEXTSHARP
I have used pdflib for this.
p = new pdflib();
/* Open the input PDF */
indoc = p.open_pdi_document("myTestFile.pdf", "");
pageCount = (int) p.pcos_get_number(indoc, "length:pages");
Docotic.Pdf library may be used to accomplish the task.
Here is sample code:
PdfDocument document = new PdfDocument();
document.Open("file.pdf");
int pageCount = document.PageCount;
The library will parse as little as possible so performance should be ok.
Disclaimer: I work for Bit Miracle.
I have good success using CeTe Dynamic PDF products. They're not free, but are well documented. They did the job for me.
http://www.dynamicpdf.com/
I've used the code above that solves the problem using regex and it works, but it's quite slow. It reads the entire file to determine the number of pages.
I used it in a web app and pages would sometimes list 20 or 30 PDFs at a time and in that circumstance the load time for the page went from a couple seconds to almost a minute due to the page counting method.
I don't know if the 3rd party libraries are much better, I would hope that they are and I've used pdflib in other scenarios with success.