I am trying to convert csv to xls in which there is Bank Account No (16 digit) need to convert it to text
I tried with EPPlus package by which xls is getting generated easily but Bank Account column gets converted to scientific value.Also tried to convert column to numeric and text but thats not working
private void csvToXls(string source,string destination,string fileName)
{
string csvFileName = source;
string excelFileName = destination+"/"+fileName+".xls";
string worksheetsName = "sheet 1";
bool firstRowIsHeader = false;
var format = new ExcelTextFormat();
format.Delimiter = '|';
format.EOL = "\n"; // DEFAULT IS "\r\n";
// format.TextQualifier = '"';
using (ExcelPackage package = new ExcelPackage(new FileInfo(excelFileName)))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
worksheet.Cells["A1"].LoadFromText(new FileInfo(csvFileName), format, OfficeOpenXml.Table.TableStyles.None, firstRowIsHeader);
foreach (var cell in worksheet.Cells["C:C"])
{
cell.Value = Convert.ToString(cell.Value);
}
foreach (var cell in worksheet.Cells["AC:AC"])
{
cell.Value = Convert.ToString(cell.Value);
}
worksheet.Cells["C:C"].Style.Numberformat.Format = "#0";
worksheet.Cells["C:C"].Style.Numberformat.Format = "#";
worksheet.Cells["AC:AC"].Style.Numberformat.Format = "#";
package.Save();
}
}
Need to convert columns to text which should not be scientific value.Please suggest
Input : In test.csv below input is there
IMDATA||12345678910124567895274|1|NAME|||||||||TEST|||||||||||TESTING||||3301003726558|TDATASTING|TESTING|27-09-2019
Getting Output :
Expected Output :
You need to provide eDataTypes to LoadFromText method for each column, if no types provide for the column it will set to the General by default
So, provide the `eDataTypes to ExcelTextFormat.
I just added for 3 columns and its worked well.
public static void csvToXls(string source, string destination, string fileName)
{
string csvFileName = source;
string excelFileName = destination + "/" + fileName + ".xls";
string worksheetsName = "sheet 1";
bool firstRowIsHeader = false;
var format = new ExcelTextFormat();
var edataTypes = new eDataTypes[] { eDataTypes.String, eDataTypes.String, eDataTypes.String };
format.DataTypes = edataTypes;
format.Delimiter = '|';
format.EOL = "\n"; // DEFAULT IS "\r\n";
// format.TextQualifier = '"';
using (ExcelPackage package = new ExcelPackage(new FileInfo(excelFileName)))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
worksheet.Cells["A1"].LoadFromText(new FileInfo(csvFileName), format, OfficeOpenXml.Table.TableStyles.None, firstRowIsHeader);
package.Save();
}
}
OR
You can try to read the text manually
public static void csvToXls(string source, string destination, string fileName)
{
string csvFileName = source;
string excelFileName = destination + "/" + fileName + ".xls";
string worksheetsName = "sheet 1";
using (ExcelPackage package = new ExcelPackage(new FileInfo(excelFileName)))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
var text = File.ReadAllText(source);
var rows = text.Split('\n');
for (int rowIndex = 0; rowIndex < rows.Length; rowIndex++)
{
var excelRow = worksheet.Row(rowIndex+1);
var columns = rows[rowIndex].Split('|');
for (int colIndex = 0; colIndex < columns.Length; colIndex++)
{
worksheet.Cells[rowIndex +1, colIndex +1].Value = columns[colIndex];
}
}
package.Save();
}
}
Related
I am a newbie to C # and have the following problem. I am currently writing a program to convert various formats (.xlsx, .xml, .resx). In the first step I would like to have the opened file displayed in a datatable. I think everything should be right, but I can't get any further. Could anyone help me, please? I'm still in despair ... Here's the code:
Main
public void MnuOpenClick(object sender, RoutedEventArgs e)
{
//Open Filedialog
OpenFileDialog openfile = new()
{
//with Filter
DefaultExt = "*.xlsx",
Filter = "Excel-Worksheets (*.xlsx)|*.xlsx|Ressource-Files (*.resx)|*.resx|Catalog-Files (*.xml)|*.xml",
};
bool? browsefile = openfile.ShowDialog();
if (browsefile == true)
{
//Path to Textbox and search for file-ending
txtFilePath.Text = openfile.FileName;
string fileName = openfile.FileName;
FileInfo fileInfo = new(fileName);
string extn = fileInfo.Extension;
//Jumps to different classes
switch (extn)
{
case ".xlsx":
XlsxReaderAndConverter xlsxReaderAndConverter = new XlsxReaderAndConverter(fileName);
xlsxReaderAndConverter.ReadExcel(fileName);
break;
case ".resx":
ReadResx(openfile.FileName);
break;
case ".xml":
ReadXML();
break;
}
}
}
Class
class XlsxReaderAndConverter : MainWindow
{
//public DataGrid dtGrid { get; set; }
//public ComboBox cmbColumn { get; set; }
public string FileName { get; set; }
public XlsxReaderAndConverter(string fileName)
{
this.FileName = fileName;
}
public void ReadExcel(string fileName)
{
//Open and create .xlsx-file
Microsoft.Office.Interop.Excel.Application excelApp = new();
//Dynamic File Using Uploader....
Microsoft.Office.Interop.Excel.Workbook excelBook = excelApp.Workbooks.Open(fileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Microsoft.Office.Interop.Excel.Worksheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelBook.Worksheets.get_Item(1); ;
Microsoft.Office.Interop.Excel.Range excelRange = excelSheet.UsedRange;
string strCellData = "";
double douCellData;
int rowCnt = 0;
int colCnt = 0;
DataTable dt = new DataTable();
for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)
{
string strColumn = "";
strColumn = (string)(excelRange.Cells[1, colCnt] as Microsoft.Office.Interop.Excel.Range).Value2;
_ = dt.Columns.Add(strColumn, typeof(string));
cmbColumn.Items.Add(colCnt);
}
for (rowCnt = 2; rowCnt <= excelRange.Rows.Count; rowCnt++)
{
string strData = "";
for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)
{
try
{
strCellData = (string)(excelRange.Cells[rowCnt, colCnt] as Microsoft.Office.Interop.Excel.Range).Value2;
strData += strCellData + "|";
}
catch (Exception)
{
douCellData = (excelRange.Cells[rowCnt, colCnt] as Microsoft.Office.Interop.Excel.Range).Value2;
strData += douCellData.ToString() + "|";
}
}
strData = strData.Remove(strData.Length - 1, 1);
_ = dt.Rows.Add(strData.Split('|'));
}
dtGrid.ItemsSource = dt.DefaultView;
excelBook.Close(true, null, null);
excelApp.Quit();
}
I'm a french student in engineering school.
I have a work to do in my company (yes I work too).
I already developped an application that take xlsx file in input, I use NPOI library.
But now I need to take csv in input file, I tried several things without success.
I just need to convert a csv file as XSSFworkbook and sheet.
I'm newbie but I really want to improve my competences with c#.
Thanks for your help.
I've found on Github a sample that could help you:
class Program
{
static void Main(string[] args)
{
string csvDocument = #"FL_insurance_sample.csv";
var lines = ReadCsv(csvDocument, delimiter: ',');
ConvertWithNPOI("NPOI.xlsx", "NPOI", lines);
}
private static bool ConvertWithNPOI(string excelFileName, string worksheetName, IEnumerable<string[]> csvLines)
{
if (csvLines == null || csvLines.Count() == 0)
{
return (false);
}
int rowCount = 0;
int colCount = 0;
IWorkbook workbook = new XSSFWorkbook();
ISheet worksheet = workbook.CreateSheet(worksheetName);
foreach (var line in csvLines)
{
IRow row = worksheet.CreateRow(rowCount);
colCount = 0;
foreach (var col in line)
{
row.CreateCell(colCount).SetCellValue(TypeConverter.TryConvert(col));
colCount++;
}
rowCount++;
}
using (FileStream fileWriter = File.Create(excelFileName))
{
workbook.Write(fileWriter);
fileWriter.Close();
}
worksheet = null;
workbook = null;
return true;
}
private static bool ConvertWithEPPlus(string csvFileName, string excelFileName, string worksheetName, char delimiter = ';')
{
bool firstRowIsHeader = false;
var format = new ExcelTextFormat();
format.Delimiter = delimiter;
format.EOL = "\r"; // DEFAULT IS "\r\n";
// format.TextQualifier = '"';
using (ExcelPackage package = new ExcelPackage(new FileInfo(excelFileName)))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetName);
worksheet.Cells["A1"].LoadFromText(new FileInfo(csvFileName), format, OfficeOpenXml.Table.TableStyles.Medium27, firstRowIsHeader);
package.Save();
}
return (true);
}
private static IEnumerable<string[]> ReadCsv(string fileName, char delimiter = ';')
{
var lines = System.IO.File.ReadAllLines(fileName, Encoding.UTF8).Select(a => a.Split(delimiter));
return (lines);
}
}
original https://github.com/Leftyx/ConvertCsvToExcel/blob/master/ConvertCsvToExcel/Program.cs
I have to read Excel(.xlsx) file. I am using OpenXML NuGet pkg.
I am trying to get the range(xlRange), so I can fetch the data from a particular cell. But not getting success. This code is created in console environment.
static void Main(string[] args)
{
bool flagDataError = false;
string sDuplicateRows = string.Empty;
string sCreatedRows = string.Empty;
string sFileTypeError = string.Empty;
string filepath = #"C:\test.xlsx";
var fileName = Path.GetFileName(filepath);
var fileExtension = Path.GetExtension(filepath);
if ((fileExtension != ".xlsx") && (fileExtension != ".xls"))
sFileTypeError = "Invalid file. \n\nPlease browse a correct Excel file to upload.";
else
{
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(filepath, false))
{
WorkbookPart workbookPart = doc.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
List<AxisData> data = new List<AxisData>();
for (int i = 5; i <= 16; i++)
{
for (int j = 2; j <= 13; j++)
{
AxisData axisDetails = new AxisData();
axisDetails.ProductCode = "AXIS " + xlRange.Cells[i, 1].Value;
axisDetails.ContractPeriod = Convert.ToDateTime(xlRange.Cells[4, j].Value);
axisDetails.SettlePrice = Convert.ToDecimal(xlRange.Cells[i, j].Value);
axisDetails.EffectiveStartDate = efectiveStartDate;
}
}
}
}
}
}
}
IEnumerable<Row> ShRows = sheetData.Elements<Row>();
var _RCount = SHRows.Count();
I have been stuck on this issue for a a day or so and need some help. In my application, I have some data in a listview, which is
public void OnHostPing(HostPinger host)
{
if (InvokeRequired)
{
Invoke(new OnPingDelegate(OnHostPing), new object[] { host });
return;
}
lock (_table)
{
ListViewItem item = (ListViewItem)_table[host.ID];
if (item != null)
{
item.SubItems[0].Text = host.HostIP.ToString();
item.SubItems[1].Text = host.HostName;
item.SubItems[2].Text = host.HostDescription;
item.SubItems[3].Text = host.StatusName;
item.SubItems[4].Text = host.SentPackets.ToString();
item.SubItems[5].Text = host.ReceivedPackets.ToString();
item.SubItems[6].Text = PercentToString(host.ReceivedPacketsPercent);
item.SubItems[7].Text = host.LostPackets.ToString();
item.SubItems[8].Text = PercentToString(host.LostPacketsPercent);
item.SubItems[9].Text = host.LastPacketLost ? "Yes" : "No";
item.SubItems[10].Text = host.ConsecutivePacketsLost.ToString();
item.SubItems[11].Text = host.MaxConsecutivePacketsLost.ToString();
item.SubItems[12].Text = host.RecentlyReceivedPackets.ToString();
item.SubItems[13].Text = PercentToString(host.RecentlyReceivedPacketsPercent);
item.SubItems[14].Text = host.RecentlyLostPackets.ToString();
item.SubItems[15].Text = PercentToString(host.RecentlyLostPacketsPercent);
item.SubItems[16].Text = host.CurrentResponseTime.ToString();
item.SubItems[17].Text = host.AverageResponseTime.ToString("F");
item.SubItems[18].Text = host.MinResponseTime.ToString();
item.SubItems[19].Text = host.MaxResponseTime.ToString();
item.SubItems[20].Text = DurationToString(host.CurrentStatusDuration);
item.SubItems[21].Text = DurationToString(host.GetStatusDuration(HostStatus.Alive));
item.SubItems[22].Text = DurationToString(host.GetStatusDuration(HostStatus.Dead));
item.SubItems[23].Text = DurationToString(host.GetStatusDuration(HostStatus.DnsError));
item.SubItems[24].Text = DurationToString(host.GetStatusDuration(HostStatus.Unknown));
item.SubItems[25].Text = PercentToString(host.HostAvailability);
item.SubItems[26].Text = DurationToString(host.TotalTestDuration);
item.SubItems[27].Text = DurationToString(host.CurrentTestDuration);
}
else
{
item = new ListViewItem(new string[]
{
host.HostIP.ToString(), host.HostName, host.HostDescription,
host.StatusName,
host.SentPackets.ToString(),
host.ReceivedPackets.ToString(), PercentToString(host.ReceivedPacketsPercent),
host.LostPackets.ToString(), PercentToString(host.LostPacketsPercent),
host.LastPacketLost ? "Yes" : "No",
host.ConsecutivePacketsLost.ToString(), host.MaxConsecutivePacketsLost.ToString(),
host.RecentlyReceivedPackets.ToString(), PercentToString(host.RecentlyReceivedPacketsPercent),
host.RecentlyLostPackets.ToString(), PercentToString(host.RecentlyLostPacketsPercent),
host.CurrentResponseTime.ToString(), host.AverageResponseTime.ToString("F"),
host.MinResponseTime.ToString(), host.MaxResponseTime.ToString(),
DurationToString(host.CurrentStatusDuration),
DurationToString(host.GetStatusDuration(HostStatus.Alive)),
DurationToString(host.GetStatusDuration(HostStatus.Dead)),
DurationToString(host.GetStatusDuration(HostStatus.DnsError)),
DurationToString(host.GetStatusDuration(HostStatus.Unknown)),
PercentToString(host.HostAvailability),
DurationToString(host.TotalTestDuration),
DurationToString(host.CurrentTestDuration)
});
What I can't seem to figure out is, how to get that data exported to Excel? I am able to export static data to Excel with this code
public static string RunSample1(DirectoryInfo outputDir)
{
if (!outputDir.Exists) throw new Exception("outputDir does not exist!");
FileInfo newFile = new FileInfo(outputDir.FullName + #"\sample1.xlsx");
if (newFile.Exists)
{
newFile.Delete(); // ensures we create a new workbook
newFile = new FileInfo(outputDir.FullName + #"\sample1.xlsx");
}
using (ExcelPackage package = new ExcelPackage(newFile))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Current Devices");
//Add the headers
//worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 1].Value = "";
worksheet.Cells[1, 2].Value = "Product";
worksheet.Cells[1, 3].Value = "Quantity";
worksheet.Cells[1, 4].Value = "Price";
worksheet.Cells[1, 5].Value = "Value";
//Add some items...
worksheet.Cells["A2"].Value = 12001;
worksheet.Cells["B2"].Value = "Nails";
worksheet.Cells["C2"].Value = 37;
worksheet.Cells["D2"].Value = 3.99;
What I can't figure out is how to get those listview items in to the spreadsheet cells instead of static data. ListViewItems doesn't seem to yield the properties I would expect. Can someone help me out a bit here?
I found a solution using Microsoft.Office.Interop.Excel instead of trying to use the EPPlus solution.
My full Code is working well except the date field in the excel file after exporting. i am passing the date field as dd/MM/yyyy data with data table but in excel i am having an issue for few rows. for example :in case of February month of 2015 if the date is in between 01/02/2015 to 12/02/2015 then it is showing as 02/01/2015 - 02/12/2015 in exported excel file . but if date is greater than or equal to 13/02/2015 then it is showing perfect. Please help.
This is the class file i wrote :
public class InteropExportToExcel
{
public InteropExportToExcel()
{
}
public static void ExportExcel(DataTable dt, string SetFileName)
{
if (dt == null || dt.Rows.Count == 0) return;
var xlApp = new Excel.Application();
//Is this used?
CultureInfo CurrentCI = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
Excel.Workbooks workbooks = xlApp.Workbooks;
Excel.Range range;
Excel.Workbook workbook = workbooks.Add();
Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;
for (var i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
for (var r = 0; r < dt.Rows.Count; r++)
{
for (var i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
}
rowRead++;
//is this used?
percent = ((float)(100 * rowRead)) / totalCount;
}
Microsoft.Office.Interop.Excel.Range columns = worksheet.UsedRange.Columns;
columns.AutoFit();
//worksheet.Rows[1].Insert();
Excel.Range newRow = (Microsoft.Office.Interop.Excel.Range)worksheet.Rows[1];
Excel.Range newCell = (Microsoft.Office.Interop.Excel.Range)newRow.Cells[1];
//newCell.Value = DateTime.Now.ToString("yyyy-MM-dd");
//xlApp.Visible = true;
string fileName = HttpContext.Current.Server.MapPath("~/TempFiles/"+SetFileName+".xlsx"); //Deleting Previous TempFile Before Saving.
if (fileName != null || fileName != string.Empty)
{
if ((System.IO.File.Exists(fileName)))
{
System.IO.File.Delete(fileName);
}
}
workbook.SaveAs(HttpContext.Current.Server.MapPath("~/TempFiles/"+SetFileName), Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //Saving Current Excel Report in TempFile Server Folder
workbook.Close();
String FileName = SetFileName + ".xlsx"; // Code to Open Save Dialog in Client Computer.
String FilePath = HttpContext.Current.Server.MapPath("~/TempFiles/");
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/ms-excel";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath + FileName);
response.Flush();
response.End();
}
public static DataTable ConvertToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
}
Calling the method of this class from the linkButton's Click event :
protected void lnkExportToExcel_lnkExportToExcel(object sender, EventArgs e)
{
int CustomPageSize = 99999999;
int CustomPageNumber = 1;
string FromDate = txtFromDate.Text;
string ToDate = txtToDate.Text;
List<int> OutputVal = new List<int>();
DataTable dtDailyComments = new DataTable();
PageSize = gvDailyComments.PageSize;
dtDailyComments = UserClass.GetDailyComments(FromDate, ToDate, CustomPageNumber, CustomPageSize, ref OutputVal);
var resultSet = from row in dtDailyComments.AsEnumerable() //Selecting Custom Selected Columns From DataTable
select new
{
SlNo = row["SlNo"].ToString(),
Comment_Date = row["CommentDate"].ToString(),
Subject = row["CommentSubject"].ToString(),
Comment = row["Comment"].ToString()
};
string SetFileName = "Daily_Comments_Report";
DataTable newDataTable = InteropExportToExcel.ConvertToDataTable(resultSet.ToList());
InteropExportToExcel.ExportExcel(newDataTable, SetFileName);
}
I managed to fix this issue by converting the date columns from database in 106 format. but why cant i use 103 format from database. that is dd/MM/yyyy. if possible then please tell me how to handle this issue.
If you like to set the format to dd/MM/yyyy try this:
...
try
{
if (dgvData.Rows.Count > 0)
{
xCellApp.Application.Workbooks.Add(Type.Missing);
for (int i = 1; i < dgvData.Columns.Count + 1; i++)
{
xCellApp.Cells[1, i] = dgvData.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dgvData.Rows.Count - 1; i++)
{
for (int j = 0; j < dgvData.Columns.Count; j++)
{
if (dgvData.Columns[j].HeaderText == "dates")
{
DateTime dt = Convert.ToDateTime(dgvData.Rows[i].Cells[j].Value.ToString());
xCellApp.Cells[i + 2, j + 1] = dt.ToString("MM/dd/yyyy");
}
else
{
xCellApp.Cells[i + 2, j + 1] = dgvData.Rows[i].Cells[j].Value.ToString();
}
}
}
xCellApp.Columns.AutoFit();
xCellApp.Visible = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
xCellApp.Quit();
}
}