Converting text file into Excel sheet

Posted by Manicse under C# on 12/26/2016 | Points: 10 | Views : 309 | Status : [Member] | Replies : 1
Hi,

I am using spire tool for converting other objects to Excel format.
I need to read data from the txt file first and then write the data into Excel. If you don't want to install MS Excel, you can use 3rd party libraries, such as this one:
https://www.nuget.org/packages/FreeSpire.XLS/.
Add a reference to Spire.Xls.dll and then use below code:

using System.IO;
using Spire.Xls;

namespace Convert_TXT_to_Excel
{
class Program
{
static void Main(string[] args)
{
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
string filepath = "test.txt";
string text = File.ReadAllText(filepath);
string[] cells = text.Split(' ');
for (int i = 0; i < cells.Length; i++)
{
//insert into the first column
sheet.Range[i+1,1].Text = cells[i];
}
workbook.SaveToFile("Result.xlsx",FileFormat.Version2010);
}
}
}


I am getting error on the
string text = File.ReadAllText(filepath);


Cannot convert the object to the string data type.
So what datatype should I make to work this.

Mani.R


Responses

Posted by: Allemahesh on: 1/2/2017 [Member] [MVP] Silver | Points: 25

Up
0
Down
Make sure that you need to give the full file path:
Example:
string path = @"c:\temp\MyTest.txt";


I have modify the your code and see my changes in bold


namespace Convert_TXT_to_Excel

{
class Program
{
static void Main(string[] args)
{
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
string filepath = @"C:\file.txt";
string text = File.ReadAllText(filepath);
string[] cells = text.Split(' ');
for (int i = 0; i < cells.Length; i++)
{
//insert into the first column
sheet.Range[i+1,1].Text = cells[i];
}
workbook.SaveToFile("Result.xlsx",FileFormat.Version2010);
}
}
}


Manicse, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response