I want to export data table in Excel sheet and saving in server directory in MVC application. Here is my code-
//ManagEmployeeController.cs
public JsonResult ExportToExcel()
{
Excel.ExcelUtlity obj = new Excel.ExcelUtlity();
DataTable dt = ConvertToDataTable(ListEmployee());
string dir = string.Format("~/Clients/ExportedData/");
var directoryToSaveFile = Server.MapPath(dir);
string uniqueNumber = DateTime.Now.ToString("yyyyMMddHHmmss");
string file = "ContactExportData.xlsx";
string newFileName = string.Format("{0}{1}", uniqueNumber, file);
if (!Directory.Exists(directoryToSaveFile))
{
Directory.CreateDirectory(directoryToSaveFile);
}
string fullFilePath = string.Format("{0}/{1}",dir,newFileName); ;
//obj.WriteDataTableToExcel(dt, "Person Details", "D:\\testPersonExceldata.xlsx", "Details");
obj.WriteDataTableToExcel(dt, "Person Details", fullFilePath, "Details");
var result = new { Success = "Success", Messaage = "SuccessMessage" };
return Json(result,JsonRequestBehavior.AllowGet);
}
The directory gets created but file does not saved here. But if I use commented code(obj.WriteDataTableToExcel(dt, "Person Details", "D:\\testPersonExceldata.xlsx", "Details");) the file gets saved on my local directory D.
//ExcelUtility.cs
public bool WriteDataTableToExcel(System.Data.DataTable dataTable, string worksheetName, string saveAsLocation, string ReporType)
{
Microsoft.Office.Interop.Excel.Workbook excelworkBook;
//
//
excelworkBook.SaveAs(saveAsLocation);;
}
What is missing in my code in order to save Excel to mentioned directory on server?
string fullFilePath = string.Format("{0}/{1}",dir,newFileName);
should be:
string fullFilePath = string.Format("{0}/{1}",directoryToSaveFile,newFileName);
Related
I have a CSV file that will be populated with different file names, source and archive location
And I would like to read the CSV file and copy/ Move each file name to an archive and stamp each file moved with date and time in the archive
my CSV "test.csv" is like this
Number FileName Source Destination**
1, Support.CSv, C:\home, C:\Support\Archive
2, Account.txt, c:\home, D:\Account\Archive
3, Support5.csv, C:\home, C:\Support\Archive
4, allusers.csv, c:\home, D:\Account\Archive
5, Users2.csv, c:\home, D:\Account\Archive
How can I achieve this , I have tried the below code but all the files are copied in the same directory and this is not what I am looking for
string sourceDir1;
string backupDir1;
var path = #"C:/test.csv";
using (TextFieldParser csvReader = new TextFieldParser(path))
{
csvReader.CommentTokens = new string[] { "#" };
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
// Skip the row with the column names
csvReader.ReadLine();
while (!csvReader.EndOfData)
{
// Read current line fields, pointer moves to the next line.
string[] fields = csvReader.ReadFields();
String sourceDir = fields[2];
string backupDir = fields[3];
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.csv");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
;
// Copy CSV files.
foreach (string f in picList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
}
// Copy text files.
foreach (string f in txtList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
Console.WriteLine(copyError.Message);
}
}
There is no need of checking source items on each loop and re-copy items again, you can check if the current file exists and then just copy it to the specific destination. In this case your code will look like this:
var path = #"C:/test.csv";
using (TextFieldParser csvReader = new TextFieldParser(path))
{
csvReader.CommentTokens = new string[] { "#" };
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
// Skip the row with the column names
csvReader.ReadLine();
while (!csvReader.EndOfData)
{
// Read current line fields, pointer moves to the next line.
string[] fields = csvReader.ReadFields();
string fileName = fields[1];
string sourceDir = fields[2];
string backupDir = fields[3];
try
{
var sourceFilePath = $#"{sourceDir}\{fileName}";
var sourceFileExists = File.Exists(sourceFilePath);
if (sourceFileExists)
{
//check if the destination directory exists
var destinationDirectory = Directory.Exists($#"{backupDir}");
if (!destinationDirectory)
{
Directory.CreateDirectory($#"{backupDir}");
}
var destinationFilePath = Path.Combine($#"{backupDir}", fileName);
File.Copy(sourceFilePath, destinationFilePath, true);
}
else
{
throw new Exception("File was not found");
}
}
catch(IOException ex)
{
throw new Exception(ex.Message);
}
}
}
You will also have to alter the destination file name by adding the timestamp.
To create the Excel files (.XLSX) using C# ASPNET I have added the Open XML and Closed XML reference from nugget packages.
I can not understand why happen that when try delete files xlsx in folder.
"the file is being used by another process."
The process is w3wp.exe
I need restart IIS on the server for delete all files in the folder.
Any suggestion?
public static void MTemptyxlxs()
{
string AppLocation = "";
AppLocation = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
AppLocation = AppLocation.Replace("file:\\", "");
foreach (string file in Directory.GetFiles(AppLocation, "*.xlsx").Where(item => item.EndsWith(".xlsx")))
{
File.Delete(file);
}
}
public static void ExportDataSetToExcel(DataSet ds)
{
string AppLocation = "";
AppLocation = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
AppLocation = AppLocation.Replace("file:\\", "");
string date = DateTime.Now.ToShortDateString();
date = date.Replace("/", "_");
string filepath = AppLocation + "\\ExcelFiles\\" + "RECEIPTS_COMPARISON_" + date + ".xlsx";
using (XLWorkbook wb = new XLWorkbook())
{
for (int i = 0; i < ds.Tables.Count; i++)
{
wb.Worksheets.Add(ds.Tables[i], ds.Tables[i].TableName);
}
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
wb.SaveAs(filepath);
}
}
I'm trying to upload an excel file, and I want to append Guid with the file name.
I'm using C# MVC for this
public ActionResult ValidateUploadedFile()
{
DataExchangeDefinitionViewModel dataExchangeDefinitionVM = new DataExchangeDefinitionViewModel();
DataExchangeDefinition dataExchangeDefinitionObj = new DataExchangeDefinition();
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
HttpPostedFileBase file = files[0];
try
{
if (Request.Files.Count > 0)
{
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
Guid guidObj = Guid.NewGuid();
fname = file.FileName + guidObj.ToString();
}
fname = Path.Combine(Server.MapPath("~/images/Uploads/ImportExcel"), fname);
if (_dataExchangeBusiness.IsExcelFile(fname)==true)
{
file.SaveAs(fname);
return Json(new { Result = "true", Message = "" });
}
else
{
return Json(new { Result = "false", Message = "" });
}
}
}
catch (Exception ex)
{
throw ex;
}
// return Json(new { Result = "OK" ,Message="File validated succesfully"});
return null;
}
Actually, the file is uploaded properly. I want to append Guid with the file name. When I append with Guid with file name it appends after the file extension.
like this OtherExpense_01.01.2011_E20.xlsx7ac9dbdb-67bb-434c-8465-6a1f7e5bfc83
i'm expecting result like this OtherExpense_01.01.2011_E20_7ac9dbdb-67bb-434c-8465-6a1f7e5bfc83.xlsx
You can use Path.GetFileNameWithoutExtension() and Path.GetExtension() methods to concatenate filename with GUID (note that both of them requires System.IO namespace):
Guid guidObj = Guid.NewGuid();
string baseName = Path.GetFileNameWithoutExtension(file.FileName);
string extension = Path.GetExtension(file.FileName);
fname = baseName + guidObj.ToString() + extension;
This is my code.
public static string LoadPackage(DirectoryInfo outputDir, string name)
{
FileInfo newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
if (newFile.Exists)
{
newFile.Delete();
newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
}
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 1;
using (ExcelPackage package = new ExcelPackage())
{
LoadSheet(package, outputDir, name);
package.SaveAs(newFile);
}
return newFile.FullName;
}
And after that i call LoadSheet method in order to fill my excel file from tsv file.
public static void LoadSheet(ExcelPackage package, DirectoryInfo
outputDir, string name)
{
var ws = package.Workbook.Worksheets.Add("Content");
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 2;
format.SkipLinesEnd = 1;
var range = ws.Cells["A1"].LoadFromText(new
FileInfo(outputDir.FullName + "\\" + name), format,
TableStyles.Medium27, false);
}
And this is my code on button click event
if (BrowseFileUpload.HasFile)
{
var name = BrowseFileUpload.PostedFile.FileName;
InputTextBox.Text = name;
LoadData.LoadPackage(new
System.IO.DirectoryInfo("C:\\Users\\Nemanja\\Downloads"), name);
InfoLabel.Text = "Your data has been imported!!!";
InfoLabel.ForeColor = System.Drawing.Color.Blue;
InfoLabel.Font.Size = 20;
}
Everything is ok i create new excel file, sheet save it but it does not load data that i need it to load inside excel file. It's only empty file or i get a error the file is corrupted recover what you can.
Can someone figure out what can be a problem based on my explanation and this code. Thank you all good people.
I think that the problem may well be with the format of your source data. I've put together the following sample, based on your code, and it works fine.
var outFile = Path.ChangeExtension(filePath, ".xlsx");
using (var p = new ExcelPackage())
{
var fmt = new ExcelTextFormat();
fmt.Delimiter = '\t';
fmt.SkipLinesBeginning = 2;
fmt.SkipLinesEnd = 1;
fmt.EOL = ((char)10).ToString(); // THIS LINE FIXED THE PROBLEM (UNIX NEWLINE)
var ws = p.Workbook.Worksheets.Add("Imported Text");
ws.Cells[1, 1].LoadFromText(new FileInfo(filePath), fmt, TableStyles.Medium27, false);
p.SaveAs(new FileInfo(outFile));
}
Try running your data through this and see if you get the same issue or not.
UPDATED
The problem was a unix-style newline in the file - EPPlus expects a windows-style newline by default
Here is my code
[HttpPost]
public ActionResult Result(FormCollection form)
{
String Date = form["date"].ToString();
String Directory = Date.Replace("-", "");
//Featch file path
String RootPath = Properties.Settings.Default.FilePath.ToString();
String FilePath = System.IO.Path.Combine(RootPath, Directory, "Call.Log.txt");
FilePath = #System.IO.Path.GetFullPath(FilePath).ToString();
if (System.IO.File.Exists(FilePath))
{
string[] lines = System.IO.File.ReadAllLines(FilePath);
foreach(string line in lines)
{
System.Diagnostics.Debug.WriteLine(line);
}
return null;
} else
{
return View("DirNotFound");
}
//return null;
}
I'm receiving date as 2015-07-27 from form. And D:\ from RootPath. As FilePath output I'm getting D:\\20150727\\Call.Log.txt. The file is really exists in the directory but I'm getting false as System.IO.File.Exists(FilePath). I need your suggestion to fix the issue.