Convert particular sheet in excel to csv - c#

How do I convert a particular sheet to CSV from Excel using C# Interop? Does it default to the first sheet or can I specify?
This is the code i am using:
private void ConvertProgsToCSV()
{
Excel.Application app = new Excel.Application();
Excel.Workbook wb = app.Workbooks.Open(txtFname.Text);
wb.SaveAs(#"C:\Temp\output.csv", Excel.XlFileFormat.xlCSVWindows);
wb.Close(false);
app.Quit();
Console.WriteLine("Done!");
}

You have to open worksheet by it's name and Select it using Select() function:
xlSheet = (Excel.Worksheet)xlBook.Worksheets["Sheet1"];
xlSheet.Select(Type.Missing);
xlBook.SaveAs("C:\Filename.csv", Excel.XlFileFormat.xlCSV,Excel.XlSaveAsAccessMode.xlNoChange);
Assuming that xlSheet is of typeInterop.Excel.WorkSheet and xlBook is of type Interop.Excel.Workbook
You can refer to this links for more info:
How to: Programmatically Select Worksheets
Working with Worksheets
C# with Excel -- How to select a sheet?

Related

How to get alt text of a table in a excel worksheet

How to get alt text of a table in a excel worksheet?
I have this code to open a Excel Workbook, but how do I get the Alternative Text of a table in a woorksheet?
string filePath = #"C:\Temp\ExcelTable.xlsx";
Excel.Application excelApp = new Excel.Application();
Excel.Workbook excel_wbk = excelApp.Workbooks.Open(filePath);
// This work if there is a shape in Worksheet 1:
string altTextShape = excel_wbk.Worksheets[1].Shapes[1].AlternativeText
// Code to get excel table alt text?
// excel_wbk.Worksheets[1].Tables[1].AlternativeText
// or excel_wbk.Worksheets[1].Table[1].AlternativeText doesn't exist
excelApp.Quit();
Alternative text doesn't exist on tables, check out this link and you'll see that alternative text is available for pivot tables and shapes and not much else.

not able to copy excel column values to specified range in another excel file

I have written a small code to copy few columns from source excel file to another excel file (destination excel file) using c#. Below is sample image of source excel file.
The expected result in destination excel file should be as shown in below image.
Below is my code
string fileTarget = #"C:\Users\sia\Desktop\Excel Automation\destination.xlsx";
string fileTemplate = #"C:\Users\sia\Desktop\Excel Automation\source.xlsx";
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbTemp, wbTarget;
Microsoft.Office.Interop.Excel.Worksheet sh;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbSource = excel.Workbooks.Open(fileTemplate, ReadOnly: false);
Microsoft.Office.Interop.Excel.Worksheet WorksheetSource = wbSource.Sheets[1];
//Copy all range in this worksheet
WorksheetSource.UsedRange.Copy(Type.Missing);
//Open destination workbook
Microsoft.Office.Interop.Excel.Workbook wbDestination = excel.Workbooks.Open(fileTarget, ReadOnly: false);
Microsoft.Office.Interop.Excel.Worksheet WorksheetDestination = wbDestination.Sheets[1];
WorksheetDestination.UsedRange.PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteAll, Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
wbDestination.SaveAs(#"C:\Users\sia\Desktop\Excel Automation\destination.xlsx");
wbSource.Close();
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
But the i'm not getting the expected format, below is the result I'm getting.
where and what modification i need to do in my existing code to get the expected result.
Thanks
You need to specify proper column and range, otherwise by default paste will go in the first column
workSheet.Range
For reference: Copy/paste cells in Excel with C#

Open XML How to programmatically group (shift select) sheets in Excel

I am trying to programmatically group (shift select) sheets in Excel using Open XML API. I know how to do it in Interop way like:
String[] sheetsToBeSelected = {"Sheet1","Sheet2","Sheet3"};
excel.Workbook workbook = ExcelApp.ActiveWorkbook;
excel.Sheets worksheets = workbook.Worksheets;
((excel.Sheets)worksheets.get_Item(sheetsToBeSelected)).Select();
Tried hard to translate it to Open XML API, but no luck. Please help.
Thanks.
Try setting the TabSelected property of SheetView. Here is the sample code
foreach(Sheet sht in myWorkBook.WorkBook.Descendants<Sheet>())
{
WorkSheetPart wrkShtPart = (WorkSheetPart)myWorkBook.GetPartById(sht.Id);
SheetViews shtViews = wrkShtPart.WorkSheet.GetFirstChild<SheetViews>();
SheetView shtView = shtViews.GetFirstChild<SheetView>();
shtView.TabSelected = null;
}

Adding .txt file that in csv format as a sheet to existing workbook in C#

I have a .txt file that is already in Comma-separated values (csv) format.
I want to add the data in the .txt file as a sheet to an open Excel workbook.
this is how I open the workbook:
var xlApp = new Excel.Application { Visible = false };
Excel.Workbook newWorkbook = xlApp.Workbooks.Add(Type.Missing);
And this is how I try to add the .txt file to the workbook:
string txt2xls = Globals.HomeDir + "\\JSL\\Data1" + ".txt";
string csv2xls = Globals.HomeDir + "\\JSL\\Data1" + ".csv";
if (File.Exists(csv2xls))
File.Delete(csv2xls);
File.Move(txt2xls, Path.ChangeExtension(txt2xls, ".csv"));
newWorkbook.Sheets.Add(csv2xls, Type.Missing, Type.Missing, Type.Missing);
The last line gave me an error (HRESULT: 0x800A03EC).
What can i do to solved this problem?
thanks!
CSV file in Excel can have allways only one worksheet. You cannot add another sheet as CSV. You will have to open the CSV separately as another Workbook and copy the Worksheet from that Workbook to your multi-sheet xlsx Workbook newWorkbook.
Use Worksheet.Copy method as described in How to: Programmatically Copy Worksheets and here.
var xlApp = new Excel.Application { Visible = false };
Excel.Workbook newWorkbook = xlApp.Workbooks.Add(Type.Missing);
Excel.Workbook csvWorkbook = xlApp.Workbooks.Open(csv2xls);
Excel.Worksheet worksheetCSV = ((Excel.Worksheet)csvWorkbook.Worksheets[1]);
Excel.Worksheet targetWorksheet = ((Excel.Worksheet)newWorkbook.Worksheets[1]);
worksheetCSV.Copy(targetWorksheet);
Also mark that
If you do not specify either Before or After, Microsoft Office Excel
creates a new workbook that contains the copied sheet.
So you can do
worksheetCSV.Copy(Type.Missing, Type.Missing);
and no need to explitly Add newWorkbook.

Export data from dataset to excel

I am trying to export data from dataset to excel and save it directly to a given path without giving me the option to open,save or cancel.
Using ExcelLibrary this is a one liner ...
DataSet myDataSet;
... populate data set ...
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", myDataSet);
See also Create Excel (.XLS and .XLSX) file from C#
This C# Excel library can also be used to export the dataset. More details about how to export can be found here.
ExcelDocument xls = new ExcelDocument();
xls.easy_WriteXLSFile_FromDataSet("ExcelFile.xls", dataset,
new ExcelAutoFormat(Styles.AUTOFORMAT_EASYXLS1), "Sheet Name");
It's not the greatest solution but here is what I did, it opens a new excel document then copies what is in the dataset, all you need to do is sort out the columns and save it.
Btw totes my first post to answer a question, hope it helps
private void cmdExport_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("excel.exe");
try
{
copyAlltoClipboard();
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();
xlexcel.Visible = true;
xlWorkBook = xlexcel.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message);
}
}
private void copyAlltoClipboard()
{
dataGridViewItems.SelectAll();
DataObject dataObj = dataGridViewItems.GetClipboardContent();
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
}
Check this DataSetToExcel
and c# (WinForms-App) export DataSet to Excel
In the first link change the code as follows:
Remove the all code that initially starts and try the following
using (StringWriter sw = new StringWriter("Your Path to save"))
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
}
}
Here's another C# library, which lets you export from a DataSet to an Excel 2007 .xlsx file, using the OpenXML libraries.
http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm
All of the source code is provided, free of charge, along with a demo application, and you can use this in your ASP.Net, WPF and WinForms applications.
Once you've added the class to your application, it just takes one function call to export your data into an Excel file.
CreateExcelFile.CreateExcelDocument(myDataSet, "C:\\Sample.xlsx");
It doesn't get much easier than that.
Good luck !
Hi i found a perfect solution Here
Just replace 'missing.value' with System.Type.Missing in the code. Also remove
oWB.Close(System.Type.Missing, System.Type.Missing, System.Type.Missing);
and
oXL.Quit();
from the code. Otherwise your excel will get closed automatically as soon as it open.

Categories