issue in text to excel file convert - excel

i m creating excel file from text file using Microsoft.Office.Interop.Excel;
here is my code
private void button1_Click(object sender, EventArgs e)
{
// Reading the text file - StreamReader include System.IO namespace
StreamReader objReader = new StreamReader(#"C:\Users\pci218\Desktop\TextToExcelFormApplication\TextToExcelFormApplication\Text\pop3.txt");// Please give the file path
string sLine = "";
ArrayList arrText = new ArrayList();// Include System.Collections.Generic namespace
while (sLine != null)
{
sLine = objReader.ReadLine();
if (sLine != null)
arrText.Add(sLine);
}
callExcel(arrText, true);
}
private void callExcel(ArrayList arrText, bool value)
{
try
{
// Change Your String here
String textString = null;
foreach (var item in arrText)
{
textString = textString + item + Environment.NewLine;
}
Clipboard.SetText(textString);
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Excel.Application();
// for excel visibility
//xlexcel.Visible = true;
// Creating a new workbook
xlWorkBook = xlexcel.Workbooks.Add(misValue);
// Putting Sheet 1 as the sheet you want to put the data within
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// creating the range
Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.Paste(CR, false);
if (value == true)
{
try
{
// saving the file as .xls
xlWorkSheet.SaveAs(#"C:\Users\U0153056\Desktop\receivedNew.xls");
}
catch (Exception)
{
MessageBox.Show("File already exist");
}
}
else
{
try
{
// saving the file as .xlsx
xlWorkSheet.SaveAs(#"C:\Users\U0153056\Desktop\receivedNew.xlsx");
}
catch (Exception)
{
MessageBox.Show("File already exist");
}
}
xlexcel.Quit();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
but i m getting "Retrieving the COM class factory for component with CLSID"
error. i dont have microsoft office installed in my PC.is tht the problem? due to that m getting this error? anyone have idea .pls help.

Unfortunately, you can't use Microsoft.Office.Interop.Excel without having Microsoft Office Excel 2007 or later version installed.
... you must have Microsoft Office Excel 2007 and Microsoft Office
Word 2007, or later versions, installed on your computer.
Check this link for more information.

Related

Not able to read excel sheet saved as xls using closedxml

I have the below code to save the data in excel sheet as .xls
public ActionResult ExportToExcel()
{
DataTable tbl = CopyGenericToDataTable(res);
tbl.TableName = "InvalidInvoices";
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(tbl);
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename= "+fileName + ".xls");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
Above is code which download the xls excel sheet at client side. It works fine the data gets saved in excel sheet.
Problem is if I try to upload this same file using below code -
if (files != null)
{
HttpPostedFileBase upload = files.FirstOrDefault();
Stream stream = upload.InputStream;
DataSet result = new DataSet();
if (upload != null && upload.ContentLength > 0)
{
if (upload.FileName.EndsWith(".xls") || upload.FileName.EndsWith(".xlsx"))
{
// ExcelDataReader works with the binary Excel file, so it needs a FileStream
// to get started. This is how we avoid dependencies on ACE or Interop:
// We return the interface, so that
IExcelDataReader reader = null;
if (upload.FileName.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (upload.FileName.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
reader.IsFirstRowAsColumnNames = false;
result = reader.AsDataSet();
reader.Close();
}
}
}
In above code I am getting error in ExcelReaderFactory.CreateBinaryReader(stream);
In stream it has the values in bytes too just on using createBinaryreader of excelreaderfactory reader has error message as 'Invalid file signature'.
Any help will be highly appreciated.
ClosedXML generates .xlsx files, not .xls files.
Check your code:
Response.AddHeader("content-disposition", "attachment;filename= "+fileName + ".xls");

Overwriting a file that is currently being used

I want to create a new sheet on an Excel workbook that is currently open/being used. In my program, I ask the user for a new worksheet name, but when I have the Excel file open, it returns me a FileNotFoundException because it "cannot access the file because it is being used by another process." Is it possible to fix this? Or should I ask the user to close the file first?
public void exportToExcel() {
String excelFileName = null; // the name/directory/address of the excel file created/selected
FileInputStream excelFileIn = null; // allows us to connect to the Excel file so we can read it
FileOutputStream excelFileOut = null; // allows us to connect to the Excel file so we can write to it
ExcelFileUtility eUtil = new ExcelFileUtility(); // used open an excel file
if(columnsQuery != null) {
try {
excelFileName = eUtil.getFile(FileExtensions.XLS);
if(excelFileName != null) {
excelFileIn = new FileInputStream(new File(excelFileName));
workbook = new HSSFWorkbook(excelFileIn);
exportColsToWorkbook(columnsQuery);
excelFileOut = new FileOutputStream(excelFileName);
workbook.write(excelFileOut);
// close everything
workbook.close();
excelFileIn.close();
excelFileOut.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}

org.apache.poi.openxml4j.exceptions.InvalidOperationException: Can't open the specified file

My code is not working, it always shows the above mentioned exception.
but I can always see the tmp file being generated.
here is the code, can someone please suggest something:
FileInputStream fis =null;
try{
fis= new FileInputStream(new File("/home/amar/Desktop/new/abc.xls"));
Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(fis);
int numOfSheets = wb.getNumberOfSheets();
System.out.println("bhargo num of sheets is " + numOfSheets);
for(int i=0; i<numOfSheets; i++){
org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(i);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = (Cell) cellIterator.next();
if (cell.getCellType() == cell.CELL_TYPE_STRING) {
System.out.println("bhargo cell value is " + cell.getStringCellValue().trim());
}
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
System.out.println("bhargo, closing the stream");
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
There are a number of issues here:
fis= new FileInputStream(new File("/home/amar/Desktop/new/abc.xls"));
Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(fis);
Firstly, as explained in the Apache POI documentation, don't use an InputStream if you have a file! It's slower and uses more memory
Secondly, XSSF is the code for working with .xlsx files, but your file is a .xls one, so that won't work.
Thirdly, Apache POI has code which will automatically work out what kind of file yours is, and create the appropriate workbook for you
Your code should therefore instead be
Workbook wb = WorkbookFactory.create(new File("/home/amar/Desktop/new/abc.xls"));
This will create the right kind of workbook, direct from the file
I was able to solve my problem.
I am working on linux so it was saving the file in the older version of excel

DataTable to excel conversion

I have a datagrid which populates a datatable, I want to export the DataTable to excel on click of a button. I am using MVVM for this application. So is it ok to implement the export feature in my view?
Secondly, as i am using xaml and desktop application, how do i capture the grid and its details.
Can any one suggest me some pointers? I am new to this.
Thanks,
Sagar
This is what i have done and it helped me:
private readonly ICommand m_ExportButtonClick;
private string ExcelFilePath = "";
public ICommand ExportButtonClick { get { return m_ExportButtonClick; } }
private void OnRunExport()
{
try
{
if (queryDatatable == null || queryDatatable.Columns.Count == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
Excell.Application excelApp = new Excell.Application();
excelApp.Workbooks.Add();
// single worksheet
Excell._Worksheet workSheet = excelApp.ActiveSheet;
// column headings
for (int i = 0; i < queryDatatable.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = queryDatatable.Columns[i].ColumnName;
}
// rows
for (int i = 0; i < queryDatatable.Rows.Count; i++)
{
// to do: format datetime values before printing
for (int j = 0; j < queryDatatable.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j + 1)] = queryDatatable.Rows[i][j];
}
}
// check fielpath
if (ExcelFilePath != null && ExcelFilePath != "")
{
try
{
workSheet.SaveAs(ExcelFilePath);
excelApp.Quit();
MessageBox.Show("Excel file saved!");
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
+ ex.Message);
}
}
else // no filepath is given, the file opens up and the user can save it accordingly.
{
excelApp.Visible = true;
}
}
catch (Exception ex)
{
MessageBox.Show("There is no data to export. Please check your query/ Contact administrator." + ex.Message);
}
}
#endregion
Here's an extension method to output to any DataTable to a csv (which excel can open)
Imports System.Text
Imports System.IO
Imports System.Runtime.CompilerServices
Module ExtensionMethods
<Extension()> _
Public Sub OutputAsCSV(ByVal dt As DataTable, ByVal filePath As String)
Dim sb As New StringBuilder()
'write column names to string builder
Dim columnNames As String() = (From col As DataColumn In dt.Columns Select col.ColumnName).ToArray
sb.AppendLine(String.Join(",", columnNames))
'write cell value in each row to string builder
For Each row As DataRow In dt.Rows
Dim fields As String() = (From cell In row.ItemArray Select CStr(cell)).ToArray
sb.AppendLine(String.Join(",", fields))
Next
'write string builder to file
File.WriteAllText(filePath, sb.ToString())
End Sub
End Module
Try googling around a little. This is a very common problem and has been asked a lot already. Here's a good answer from this SO question
public static void ExportToExcel<T>(IEnumerable<T> exportData)
{
Excel.ApplicationClass excel = new Excel.ApplicationClass();
Excel.Workbook workbook = excel.Application.Workbooks.Add(true);
PropertyInfo[] pInfos = typeof(T).GetProperties();
if (pInfos != null && pInfos.Count() > 0)
{
int iCol = 0;
int iRow = 0;
foreach (PropertyInfo eachPInfo in pInfos.Where(W => W.CanRead == true))
{
// Add column headings...
iCol++;
excel.Cells[1, iCol] = eachPInfo.Name;
}
foreach (T item in exportData)
{
iRow++;
// add each row's cell data...
iCol = 0;
foreach (PropertyInfo eachPInfo in pInfos.Where(W => W.CanRead == true))
{
iCol++;
excel.Cells[iRow + 1, iCol] = eachPInfo.GetValue(item, null);
}
}
// Global missing reference for objects we are not defining...
object missing = System.Reflection.Missing.Value;
// If wanting to Save the workbook...
string filePath = System.IO.Path.GetTempPath() + DateTime.Now.Ticks.ToString() + ".xlsm";
workbook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled, missing, missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
// If wanting to make Excel visible and activate the worksheet...
excel.Visible = true;
Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet;
excel.Rows.EntireRow.AutoFit();
excel.Columns.EntireColumn.AutoFit();
((Excel._Worksheet)worksheet).Activate();
}
}

Can't copy a Worksheet that contains a Chart using EPPLUS

I'm trying to copy a worksheet that contains a chart, but when I try to do it, my code fires a "package relationship with specified id does not exist for the source part" exception, what are possible reasons for this? *If I remove the chart from the template, everything works fine.
Here's my code:
public void GenerateFromTemplate(DirectoryInfo outputPath, FileInfo templateFile,
string newFileName, List<Dictionary<string, string>> cellDataList)
{
try
{
using (ExcelPackage p = new ExcelPackage(templateFile, true))
{
bool first = true;
foreach (Dictionary<string, string> cellData in cellDataList) {
Logger.LogInfo("Adding new Sheet...");
ExcelWorksheet currentWorkSheet;
if (first)
{
currentWorkSheet = p.Workbook.Worksheets[1];
first = false;
}
else {
currentWorkSheet = p.Workbook.Worksheets.Copy("Ticker", "Ticker" + p.Workbook.Worksheets.Count);
}
foreach (KeyValuePair<string, string> cell in cellData)
{
Logger.LogInfo(cell.Key + "cell value set to" + cell.Value);
currentWorkSheet.Cells[cell.Key].Value = cell.Value;
}
}
Byte[] bin = p.GetAsByteArray();
string file = outputPath + newFileName;
Logger.LogInfo("Writing Excel File to " + file);
File.WriteAllBytes(file, bin);
Logger.LogInfo("Writing Done");
}
}
catch (Exception ex)
{
Logger.LogError(ex);
}
}
Regards!

Resources