Controller
[HttpPost]
public ActionResult Import(HttpPostedFileBase excelFile)
{
if (excelFile == null || excelFile.ContentLength == 0)
{
ViewBag.Error = "Please select a excel file<br>";
return View("Index");
}
else
{
if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx") || excelFile.FileName.EndsWith("csv"))
{
string fileName = Path.GetFileName(excelFile.FileName);
string path = Path.Combine(Server.MapPath("~/Content"), fileName);
//string path = Server.MapPath("~/Content/" + excelFile.FileName);
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
excelFile.SaveAs(path);
//Read data from excel file
MExcel.Application application = new MExcel.Application();
MExcel.Workbook workbook = application.Workbooks.Open(path);
MExcel.Worksheet worksheet = workbook.ActiveSheet;
MExcel.Range range = worksheet.UsedRange;
List<PH> publicholidays = new List<PH>();
for (int row = 0; row <= range.Rows.Count; row++)
{
PH ph = new PH();
ph.Subject = ((MExcel.Range)range.Cells[row, 1]).Text;
ph.StartDate = ((MExcel.Range)range.Cells[row, 2]).Text;
ph.EndDate = ((MExcel.Range)range.Cells[row, 4]).Text;
publicholidays.Add(ph);
}
ViewBag.Publicholidays = publicholidays;
return View("Success");
}
else
{
ViewBag.Error = "Incorrect file type<br>";
return View("Index");
}
}
}
I want to import a .csv file but why doesn't it work while when i try to import a normal .xls files, it works? Is there something wrong with my code or is it that I can't import .csv files this way?
Related
This is the space in my Controller section and I would like to rectify the code
public ActionResult UploadFiles(FileDetails fileDetails)
{
for(int i=0;Request.Files.Count > i;i++)
{
if (Request.Files.Count > 0)
{
var file = Request.Files[i];
var fileType = Path.GetExtension(file.FileName); //-> I have declared the variable but I don't know how to create file type using if-else condition
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/UploadFileDetails/"), fileName);
file.SaveAs(path);
fileDetails.FileName = fileName;
}
else
{
if (file != null && file.ContentLength > 0)
{
var imageName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/FileImage/"), imageName);
file.SaveAs(path);
fileDetails.Imagename = imageName;
}
}
}
}
_context.FileDetails.Add(fileDetails);
_context.SaveChanges();
return RedirectToAction("UploadFiles", "FileManagement");
}
If value=1 is files and value=2 is image files how to split the extensions?
public ActionResult ExcelFile(IEnumerable < HttpPostedFileBase > excelFile) {
try {
if (excelFile != null) {
foreach(var singleExcel in excelFile) {
string path = "~/ExcelFolder/";
singleExcel.SaveAs(Server.MapPath(path + singleExcel.FileName));
using(FileStream fs = new FileStream(Server.MapPath(path + singleExcel.FileName), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
using(ExcelPackage package = new ExcelPackage(fs)) {
ExcelWorksheet sheet = package.Workbook.Worksheets[1];
int startRowNumber = sheet.Dimension.Start.Row;
int endRowNumber = sheet.Dimension.End.Row;
int startColumnNumber = sheet.Dimension.Start.Column;
int endColumnNumber = sheet.Dimension.End.Column;
if (endColumnNumber > 26) {
for (int currentColumnNumber = endColumnNumber; startColumnNumber < currentColumnNumber; currentColumnNumber--) {
var cellValue = sheet.Cells[startRowNumber, currentColumnNumber].Value ? .ToString();
if (!string.IsNullOrWhiteSpace(cellValue)) {
if (cellValue == "延人公里小計") {
sheet.DeleteColumn(currentColumnNumber);
sheet.Cells[1, currentColumnNumber].Value = "小計";
//return fsr;
package.SaveAs(
new FileInfo(# "C:\Users\leon0944\Desktop\123\" + singleExcel.FileName));
break;
}
}
}
}
}
}
}
Hello,when I upload many Excel to the file then read every single Excel to do someting.then i got error in ExcelPackage package = new ExcelPackage(fs) this row
error message :System.Runtime.InteropServices.COMException: HRESULT:
0x8003001D (STG_E_WRITEFAULT)
sometime is working normally sometime I got error,Please tell me How Can I fix this. The problem existed for several days.
I have tried POI versions
1.poi-src-3.9-20121203 also with
2.poi-bin-3.10-beta2-20130904
But not able to read .xls file
Getting below error
"
org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]"
Note:I am able to read .xlsx file.
This is for .xlsx
try {
// Get the workbook object for XLSX file
XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(path));
// Get first sheet from the workbook
XSSFSheet sheet = (XSSFSheet) wBook.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
// Iterate through each rows from first sheet
Iterator<org.apache.poi.ss.usermodel.Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
StringBuffer data = new StringBuffer();
row = (XSSFRow) rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
int count = 0;
while (cellIterator.hasNext()) {
count++;
cell = (XSSFCell) cellIterator.next();
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
data.append(cell.getRawValue()+ ";");
}else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN)
{
data.append(cell.getBooleanCellValue() + ";");
} else if(cell.getCellType() == Cell.CELL_TYPE_STRING)
{
data.append(cell.getStringCellValue() + ";");
}
else if(cell.getCellType() == Cell.CELL_TYPE_BLANK)
{
data.append("" + ";");
}
else
{
data.append(cell + ";");
}
}
String finalStr = data.toString().substring(0, (data.length()-1));
System.out.print(finalStr);
}
} catch (Exception ioe) {
ioe.printStackTrace();
}
Thia is for .xls
try {
// Get the workbook object for XLS file
HSSFWorkbook wBook = new HSSFWorkbook(new FileInputStream(path));
// Get first sheet from the workbook
HSSFSheet sheet = (HSSFSheet) wBook.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
// Iterate through each rows from first sheet
Iterator<org.apache.poi.ss.usermodel.Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
StringBuffer data = new StringBuffer();
row = (HSSFRow) rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
int count = 0;
while (cellIterator.hasNext()) {
count++;
cell = (HSSFCell) cellIterator.next();
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
data.append(cell.getRawValue()+ ";");
}else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN)
{
data.append(cell.getBooleanCellValue() + ";");
} else if(cell.getCellType() == Cell.CELL_TYPE_STRING)
{
data.append(cell.getStringCellValue() + ";");
}
else if(cell.getCellType() == Cell.CELL_TYPE_BLANK)
{
data.append("" + ";");
}
else
{
data.append(cell + ";");
}
}
String finalStr = data.toString().substring(0, (data.length()-1));
System.out.print(finalStr);
}
} catch (Exception ioe) {
ioe.printStackTrace();
}
Try using org.apache.poi.ss.usermodel.Workbook. It can be used for both .xls and .xlsx file
Workbook workbook = null;
if (suffix.equalsIgnoreCase("xls")) {
workbook = (Workbook) new HSSFWorkbook(new POIFSFileSystem(
new FileInputStream(assetFile)));
} else if (suffix.equalsIgnoreCase("xlsx")) {
InputStream inp = new FileInputStream(assetFile);
workbook = new XSSFWorkbook(inp);
inp.close();
}
You need poi-ooxml to read xlsx format too.
Add this Maven dependency
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
For xls use
Workbook = new HSSFWorkbook(new FileInputStream(new File("fileName")));
For xlsx use
Workbook = workbook = new XSSFWorkbook(new FileInputStream(new File("fileName")));
If you don't know the file format before reading and sometimes finding .xls or .xlsx file extension may not be always good enough to find the actual file format. In that case do like this
Workbook workbook;
try {
workbook = new HSSFWorkbook(new FileInputStream(new File("fileName")));
System.out.println(" Reading XLS file");
} catch (OfficeXmlFileException e) {
System.out.println(" Reading XLSX file");
workbook = new XSSFWorkbook(new FileInputStream(new File("fileName")));
}
Rest is all the same .xls and .xlsx
An easier way to create workbook by autodetecting the input is
Workbook workbook = WorkbookFactory.create(new File("fileName"));
Hi I using VisualStudio 2012 and I have created web site which reads info (from .csv) from external ftp site. When I running it on local host everything works fine, but then I deployed it to azure web sites it is not working, just show zeros everywhere were should be numbers. (Dont get info from ftp)
public static List<ApiClient.Models.StatsList> GetStatsData(string Ticket, DateTime start, DateTime end, int CampaignId, String CampaignName)
{
//--------------------------------------------------------------------------------------------------------
//Gets stats from GetAdsStats service (included: Banner id, impressions, and clicks)
//--------------------------------------------------------------------------------------------------------
List<ApiClient.Models.StatsList> FullList = GetAdStatsService.GetAdsStats(Ticket, start, end, CampaignId);
List<LikesDislikesList> LikeDislike = new List<LikesDislikesList>();
//--------------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------------
string day;
string month;
if (DateTime.Today.AddDays(-1).Day.ToString().Count() == 1)
{
day = "0" + DateTime.Today.AddDays(-1).Day;
}
else
{
day = DateTime.Today.AddDays(-1).Day.ToString();
}
if (DateTime.Today.Month.ToString().Count() == 1)
{
month = "0" + DateTime.Today.Month;
}
else
{
month = DateTime.Today.Month.ToString();
}
try
{
string uri = "ftp://siteAdres" + CampaignName.Replace(" ", "_") + "_Optimizing_events_" + day + "-" + month + "-" + DateTime.Today.Year + ".csv";
Uri serverUri = new Uri(uri);
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return FullList;
}
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential("username", "password");
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader csvStream = new StreamReader(response.GetResponseStream());
//--------------------------------------------------------------------------------------------------------
//Read Likes/Dislikes from csv file stream
//--------------------------------------------------------------------------------------------------------
using (var rd = csvStream)
{
int iname = -1;
int ilikes = -1;
int idislikes = -1;
while (!rd.EndOfStream)
{
var raw = rd.ReadLine().Split((char)9);
if (rd.Peek() == -1)
{
break;
}
if (ilikes == -1 || idislikes == -1)
{
for (int i = 0; i < raw.Length; i++)
{
if (raw[i] == "Event name")
iname = i;
if (raw[i] == "Custom Event 14")
ilikes = i;
if (raw[i] == "Custom Event 15")
{
idislikes = i;
raw = rd.ReadLine().Split((char)9);
}
}
}
else
{
LikeDislike.Add(new LikesDislikesList() { Likes = Convert.ToInt32(raw[ilikes]), Dislikes = Convert.ToInt32(raw[idislikes]), Name = raw[iname] });
}
}
}
response.Close();
}
catch(Exception ex)
{
log4net.Config.XmlConfigurator.Configure();
log.Warn("GetAdStatsService.cs " + ex);
}
//--------------------------------------------------------------------------------------------------------
//Add like/dislike values for certain banners
//--------------------------------------------------------------------------------------------------------
foreach (var element in FullList)
{
foreach (var el in LikeDislike)
{
if (element.name == el.Name)
{
element.Likes = el.Likes;
element.Dislikes = el.Dislikes;
}
}
}
return FullList;
}
}
}
Check FtpWebResponse.StatusCode before calling response.GetResponseStream(). You are probably having come kind of connection error. My guess would be firewall settings on your Azure VM.
I have to create a .xls file from the data displayed in a table in my page. This happens when the user clicks 'export' button. I have the following code for it and it is created okay. Now, I want to open this file in the same click. How should I open it for user to see it?
string filePath = "C:/Upload/Stats_" + viewModel.SelectedTest.ToString() + ".xls";
//write the header
using (var pw = new StreamWriter(filePath, true))
{
pw.WriteLine(String.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}", "Month", "Total Users", "K",
"T", "G", "Detail", "GS",
"BI", "GHF","A"));
//write to the file
for (int i = 0; i < 12; i++)
{
pw.WriteLine(
String.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}", viewModel.Months[i],
viewModel.M[i], viewModel.MKau[i],
viewModel.MTech[i], viewModel.MGew[i],
viewModel.MDet[i], viewModel.MGes[i],
viewModel.MBea[i], viewModel.MGesHf[i],viewModel.MAug[i]));
pw.Flush();
}
pw.Close();
}
Here I would like to open it.
I had the same 'requirement' to be able to export to xls, and instead I gave the client an export to csv, which will open in excel if you are on a machine with excel installed but is also available to other systems. I achieved it like this.
Create an extension method that supports .AsCsv, which was taken largely from Mike Hadlow's implementation
public static class EnumerableExtensions
{
public static string AsCsv<T>(this IEnumerable<T> items) where T : class
{
var csvBuilder = new StringBuilder();
var properties = typeof(T).GetProperties();
foreach (T item in items)
{
string line = string.Join(",", properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray());
csvBuilder.AppendLine(line);
}
return csvBuilder.ToString();
}
private static string ToCsvValue<T>(this T item)
{
if (item is string)
{
return string.Format("\"{0}\"", item.ToString().Replace("\"", "\\\""));
}
double dummy;
if (double.TryParse(item.ToString(), out dummy))
{
return string.Format("{0}", item.ToString());
}
return string.Format("\"{0}\"", item.ToString());
}
}
Then you would need set your controller method to return a FileContentResult and have some logic like this within the controller method:
var outputModel = viewModel.ToList().Select(model => new
{
Months = model.Months
M = model.M[i],
MKau= model.MKau,
MTech = model.MTech,
MGew = model.MGew,
MDet = model.MDet,
MGes = model.MGes,
MBea= model.MBea,
MGesHf= model.MGesHf
});
string csv = "\"Month\",\"Total Users\",\"K\",\"T\",\"G\",\"Detail\",\"GS\",\"BI\",\"GHF\",\"A\""
+ System.Environment.NewLine
+ outputModel.AsCsv();
string fileName = "Stats_" + viewModel.SelectedTest.ToString() + ".csv"
return this.File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", fileName);