I am reading an excel file using my controller. I am storing all the lines of CSV file in an array. When I print it out, I can see the contents of array. But when I iterate through each of the lines and split by comma, I get nothing and as a result I can't store read values.
Here is a sample of my output along with code:
VAWC Neptune flat file is my file. 206 are number of lines in file. Then I am printing line along with its length. And when this line is splitted by commas, I see only first output else everything is empty.
However as we keep on reading other lines, this splitted array doesn't appear.
Here is the section of code which I am using:
//files is only having a single file named VAWC Neptune flat file - new meters for inventory.csv
public ActionResult ReadFile(IEnumerable<HttpPostedFileBase> files)
{
var fileName = Path.GetFileName(files.First().FileName);
var destinationPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
files.First().SaveAs(destinationPath);
try
{
string[] read = System.IO.File.ReadAllLines(destinationPath);
System.Diagnostics.Debug.WriteLine(read.Length);
for (int i = 0; i < read.Length; i++)
{
System.Diagnostics.Debug.WriteLine(read[i]);
List<string> s = read[i].Replace(Environment.NewLine,"").Split(new char[] { ',' }, StringSplitOptions.None).ToList<string>();
System.Diagnostics.Debug.WriteLine("Length of words in line:" + s.Capacity);
for (int j = 0; j < s.Capacity; j++)
{
System.Diagnostics.Debug.WriteLine("Data:s[" + j + "]" + s[j]);
}
}
}
I have tried so many possible ways but nothing has worked.
From Excel to CSV, right. This is how I would do it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(#"C:\Users\Ryan\Desktop\Coding\DOT.NET\Samples C#\Excel Workbook - Save Each Sheet as a CSV File\Book1.xlsx");
xlApp.Visible = true;
foreach (Excel.Worksheet sht in xlWorkBook.Worksheets)
{
sht.Select();
xlWorkBook.SaveAs(string.Format("{0}{1}.csv", #"C:\Users\Ryan\Desktop\Coding\DOT.NET\Samples C#\Excel Workbook - Save Each Sheet as a CSV File to CSV\", sht.Name), Excel.XlFileFormat.xlCSV, Excel.XlSaveAsAccessMode.xlNoChange);
}
xlWorkBook.Close(false);
}
}
}
Related
It should let me choose a text file from my computer. There will be numbers in this text file. These numbers will be separated by “white-space” characters (hint: make sure you consider ALL of the white-space characters otherwise your program will probably fail). Decimal digits of decimal numbers will be separated by commas. The amount of numbers in the text file is uncertain. When I select the file and click on the button, I should see all the numbers in the text file sorted in the order from BIG to SMALL.
The content of a sample text file looks like this:
56 45 6 2 789
9 349 -87
11
4,34 -198,456
65
9,85 45
-1
99,456
877 56 34 4
I work on Visual Studio 2017.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace TestUygulamasi {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) //get file and paste to testbox
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK) {
try {
if ((myStream = openFileDialog1.OpenFile()) != null) {
using (myStream) {
textBox1.Text = File.ReadAllText(openFileDialog1.FileName);
}
}
} catch (Exception ex) {
MessageBox.Show("Error: File has not read. Error: " + ex.Message);
}
}
}
private void button2_Click(object sender, EventArgs e)//Sorting Button
{
string numbers = textBox1.Text;
string[] arr;
arr = numbers.Split(' ');
Array.Sort(arr);
string sorting = int.Parse(textBox2.Text);
for (int i = 0; i < arr.Length; ++i) {
sorting = sorting + arr[i] + "\n";
//sorting = arr[i] + "\n";
}
textBox2.Text = Convert.ToString(sorting);
//listBox1.Items.Add("\n" + sorting + "\n");
//MessageBox.Show(sorting);
}
}
}
I can't sort the numbers in descendly.
You could use Linq for the purpose.
var str = textBox1.Text;
var currentCulture = (CultureInfo)CultureInfo.InvariantCulture.Clone();
currentCulture.NumberFormat.NumberDecimalSeparator = ",";
currentCulture.NumberFormat.NumberGroupSeparator = ".";
var numbers = str.Split(new string[] { " ",Environment.NewLine },StringSplitOptions.RemoveEmptyEntries)
.Select(num=> decimal.Parse(num,currentCulture))
.OrderBy(num=>num);
textBox1.Text = string.Join(Environment.NewLine,numbers);
The other answer is this. I did not write this code. Person who wrote the code has deleted the code and his/her comments. Why he/she did it? I dont know. I hope he/she answer again under this question. I am new in the website so I could not vote up his/her answer. Thank you secret hero who I lost.
List<decimal> nums = new List<decimal>();
for (int i = 0; i < textBox1.Lines.Count(); ++i)
{
string[] line = textBox1.Lines[i].Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
foreach (string s in line)
{
nums.Add(decimal.Parse(s, NumberStyles.Number, new CultureInfo("tr-TR")));
}
}
foreach (decimal d in nums.OrderByDescending(x => x))
{
listBox1.Items.Add(d.ToString());
}
I am trying to alphabetize all the words in a text file using C#. I am able to read the file and fill the list properly. I am then able to iterate through the list and print to the console. However, while I am iterating, I am also trying to write to an output file. I cannot seem to pinpoint why the output file is empty while the console has all the words printed properly. The file sortedProposal.txt is created, but is empty.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IO_Practice
{
class Program
{
static void Main(string[] args)
{
//get the directory of the text file
string directory = Directory.GetCurrentDirectory();
string cd = (Path.Combine(directory, #"..\..\"));
string infileHandle = cd + "AModestProposal.txt";
//print to screen for testing
Console.WriteLine(infileHandle);
//Holds all the words in the story
List<string> words = new List<string>();
//Holds the words from one line
string[] wordHolder;
//Holds each line as it's read
string line;
using (StreamReader sr = new StreamReader(infileHandle))
{
while ((line = sr.ReadLine()) != null)
{
//print to console
Console.WriteLine(line);
//split line into array
wordHolder = line.Split(' ');
//add array to vector
words.AddRange(wordHolder);
}
}
words.Sort();
//Debug
Console.WriteLine("Length of List: " + words.Count());
//create the outfile
string outfileHandle = cd + "sortedProposal.txt";
using(StreamWriter sw = new StreamWriter(outfileHandle)) {
foreach(string word in words)
{
sw.WriteLine(word);
//Debug
Console.WriteLine(word);
}
}
}
}
}
I am trying to export the data from a data table into xml file. I have this part working but when a record does not have any data or a white space it still writes the it in the xml file with XML:space Preserved.
I want to ignore the columns and not have them in xml file if they do not have any data in them
example of the xml file it is producing now
I want customer street 3 and 4 nodes to be not printed if they don't have any values in them.
here is my code
using System.IO;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml.Linq;
using System;
using System.Collections.Generic;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System.Xml;
namespace InvoicePrintProgram
{
class XMLGenerator
{
//Defining method that generates XMl Files
public void Start(String XmlFilepath, string XMlFileName, DataTable DT, int PageCountOut, int SequenceCountOut, int[] PrefIndex/*, int[] SequenceIndex, IEnumerable<String> chunk, int IndexCount out int IndexCountOut*/)
{
// Creates Xml file from datatable using the wrtieXml method
FileStream streamWrite = new FileStream(XmlFilepath, System.IO.FileMode.Create);
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Indent = true;
//settings.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1")
settings.Encoding = System.Text.Encoding.UTF8;
settings.CloseOutput = true;
settings.CheckCharacters = true;
settings.NewLineChars = "\r\n";
DT.WriteXml(streamWrite, XmlWriteMode.IgnoreSchema);
You can create a List of Object from that DataTable and use something like this:
List<string> xml_string = new List<string>();
xml_string.Add("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
xml_string.Add("anything you need as header");
foreach(string current_string in your_object_of_DataTable)
{
if(current_string!=null || current_string.Trim()!="")
{
xml_string.Add("<Your Tag>"+current_string+"</Your Tag>");
}
}
try
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"D:\xml_file_name.xml"))
{
foreach (string line in xml_string)
{
file.WriteLine(line);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
MessageBox.Show("File exported.");
}
I need convert the xlsx file to csv file and I have tried this article:
http://www.codeproject.com/Articles/246772/Convert-xlsx-xls-to-csv
The project works on ExcelDataReader library.
In local debug F5 with visual studio I don't have error and the conversion is worked, but If launch the aspx page on the server I have this error:
Compiler Error Message: CS0246: The type or namespace name 'Excel' could not be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 16: FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
Line 17:
Line 18: Excel.IExcelDataReader excelReader = Excel.ExcelReaderFactory.CreateOpenXmlReader(stream);
Line 19: DataSet result = excelReader.AsDataSet();
Line 20: excelReader.Close();
What am I missing?
What's wrong with this code?
Thank you in advance.
using System;
using System.Data;
using System.IO;
public partial class Default2 : System.Web.UI.Page
{
DataSet result = new DataSet();
string filePath = #"\\...\Tbl.xlsx";
protected void UploadButton_Click(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
Excel.IExcelDataReader excelReader = Excel.ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.Close();
result.Tables[0].TableName.ToString();
string csvData = "";
int row_no = 0;
int ind = 0;
while (row_no < result.Tables[ind].Rows.Count)
{
for (int i = 0; i < result.Tables[ind].Columns.Count; i++)
{
csvData += result.Tables[ind].Rows[row_no][i].ToString() + ",";
}
row_no++;
csvData += "\n";
}
string output = #"\\...\target.csv";
StreamWriter csv = new StreamWriter(#output, false);
csv.Write(csvData);
csv.Close();
}
}
<add key="EXCEL" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="{0}";Extended Properties="Excel 8.0;HDR=NO;IMEX=1;"" />
You may need this entry in your web.config
I guess for using Excel object lib. you alredy installed the PIAs. If so, then the refrence will pointing to the GAC and not the local path. So in your using statement you need to give the full path(you can see the path thru the property of the added Excel reference in the VS)
Or You can use like
using Excel = Microsoft.Office.Interop.Excel
Refer: http://msdn.microsoft.com/en-IN/library/dd264733.aspx
You have created the virtual directory in IIS for project on the server ?
I don't really know what's the problem and it looks like you're tied since you can't install anything on the server.
I suggest to try to copy all the data in a .txt file and use the find/replace feature (or make a little console program that is going to replace every line of code)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImportComuni
{
class Program
{
static void Main(string[] args)
{
int i = 1;
StreamReader reader = File.OpenText("d:\\comunidatabase.txt");
StreamWriter writer = new StreamWriter("d:\\mysqlcomuni.csv");
string line = "";
while ((line = reader.ReadLine()) != null)
{
writer.WriteLine(i + "," + "\"" + line + "\"," + "\"" + a + "\"");
i++;
}
}
}
}
assuming the first line is a and the second is c, your output will be:
1, "a", "a"
2, "c", "c"
now you can copy these values in the INSERT INTO SQL or MySQL statement.
Otherwise create a notepad txt file, add the colons on the top of it:
id, name, country
1, "a", "a"
2, "c", "c"
and so on
now save it as "File.csv"
look at this for more informations about how to import your csv file, or manually insert your data
http://www.mysqltutorial.org/import-csv-file-mysql-table/
Recently we have encounter this issue about exporting reports to excel file using infragistics library.
Our report table contains more or less 1.26 million records as of now. We are trying to create an excel(2007) file for this, so approximately this will be 2 worksheets because only about 1million rows is supported by excel 2007 per sheet.
We have no problem during the creation of worksheets and during the filling of data into the worksheet, memory is manageable at this point.
Our problem is when writing the excel data into the stream(file, memory).
The memory consumption is just too high and when it reaches 1.8GB it will no longer continue.
P.S. This is a summary report, the client wants this in a single excel file.
Your recommendations are much appreciated!!!
Below is the code that i have pulled out from the actual source but i have replaced the data retrieval part and instead use a dummy data.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Runtime;
using System.Diagnostics;
using Infragistics.Excel;
namespace ConsoleApplication1
{
class Program
{
static bool tip = true;
static void Main(string[] args)
{
var xls = Workbook.MaxExcelRowCount;
var xlsx =Workbook.MaxExcel2007RowCount;
var wb = new Workbook(WorkbookFormat.Excel2007, WorkbookPaletteMode.StandardPalette);
var ws = wb.Worksheets.Add("Sheet1");
var sheetCtr = 1;
var limit = 1256898;
var rr = 0;
for (var row = 0; row < limit; row++)
{
if (rr >= xlsx - 1)
{
//create new worksheet if row exceeded the limit
ws = wb.Worksheets.Add("Sheet" + sheetCtr.ToString());
rr = 0;
ClearMemory();
}
for (var col = 0; col < 10; col++)
{
ws.Rows[rr].Cells[col].Value = string.Format("data{0}-{1}", row, col);
}
Console.Write("Row=");
Console.Write(row.ToString());
Console.WriteLine();
rr++;
}
Console.Write("Saving worksheet...");
//this part uses too much memory
wb.Save("wb2.xlsx");
Console.WriteLine("Workbook saved.");
Console.WriteLine("Done");
Console.Read();
}
static void ClearMemory()
{
try
{
System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
if (tip == true)
{
proc.MaxWorkingSet = (IntPtr)((int)proc.MaxWorkingSet - 1);
proc.MinWorkingSet = (IntPtr)((int)proc.MinWorkingSet - 1);
}
else
{
proc.MaxWorkingSet = (IntPtr)((int)proc.MaxWorkingSet + 1);
proc.MinWorkingSet = (IntPtr)((int)proc.MinWorkingSet + 1);
}
tip = !tip;
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}