private void btn_gnrt_files_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "")
{
//reading text file
FileInfo theSourceFile = new FileInfo(#"" + textBox1.Text);
StreamReader reader = theSourceFile.OpenText();
String filename = "";
String text = "";
do
{
text = reader.ReadLine();
if (text != null)
{
//MessageBox.Show(""+state);
String[] fname = text.Split('|'); //writiting file
if (state == true)
{
filename = fname[1];
filename.TrimStart();
//MessageBox.Show(filename);
Excel.Application excel = new Excel.Application();
excel.Visible = true;
//true is append parameter
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(#"" + textBox2.Text + #"\" + filename.TrimStart() + ".csv", true))
writer.WriteLine(text.Replace("|", ","));
I get excel files with data through this code. but i cant
put column headers to excel sheets. plz tell me how to add these headers
<<reg no,br no,pr no,curency>>
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
System.Windows.MessageBox.Show("Excel is not properly installed!!");
return;
}
xlWorkBook = xlApp.Workbooks.Add();
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "reg no";
xlWorkSheet.Cells[1, 2] = "br no"
xlWorkSheet.Cells[1, 3] = "pr no"
xlWorkSheet.Cells[1, 4] = "curency";
And then do your business...
Column headers are just regular cells in Excel (or CSV), so add them as a first line.
Add that header-line before you start the loop to write the data lines.
Related
I want to append the column to the end of an existing excel file with Microsoft.Office.Interop.Excel in c#, I use Microsoft excel 2007, here is my code:
public void UpdateExcel_MSInterop(
string ExcelFile)
{
Microsoft.Office.Interop.Excel.Application xlApp = null;
Workbook xlWorkbook = null;
try
{
//define ms excel application
xlApp = new Microsoft.Office.Interop.Excel.Application();
//
int Hwnd = xlApp.Hwnd;
xlApp.DisplayAlerts = false;
//
xlWorkbook = xlApp.Workbooks.Open(ExcelFile, Type.Missing, true);
int SheetIndex = 1;
foreach (Worksheet objSHT in xlWorkbook.Worksheets)
{
if (SheetIndex == 1)// ExcelSheetFullName.Substring(0, ExcelSheetFullName.Length - 1))
{
Range rng = objSHT.UsedRange;
int colCount = rng.Columns.Count;
int rowCount = rng.Rows.Count;
Range newRng = objSHT.get_Range(objSHT.Cells[1, 1], objSHT.Cells[1, colCount]).EntireColumn.Insert(Missing.Value,XlInsertShiftDirection.xlShiftToRight);
newRng.Cells[1, colCount + 1] = "State";
for (int r = 2; r <= rowCount; r++)
{
newRng.Cells[r, colCount + 1] = Products.Rows[r - 2]["state"].ToString();
}
break;
}
SheetIndex++;
}
xlWorkbook.Save();
if (xlWorkbook != null)
xlWorkbook.Close(SaveChanges:true);
if (xlApp != null)
xlApp.Quit();
}
catch (Exception ex)
{
if (xlWorkbook != null)
xlWorkbook.Close();
if (xlApp != null)
xlApp.Quit();
xlWorkbook = null;
xlApp = null;
MessageBox.Show(ex.Message + "\n" + ex.StackTrace.ToString());
throw ex;
}
}
I get error:
object dose not contain a definition for get_Range
How to fix this error, or if my approach is wrong how to append column to the end of an existing excel file,please give me example,Thanks for help.
I have a form that allows user to select item from a list on a grid and allows them to export the data corresponding to the selected items. The data should be exported to the existing excel template. I tried some codes but what happens is when the downloaded excel file is opened it just shows blank. Can you please help me why it happens and what's wrong with my code.
Below is my code: Thanks in advance
try
{
UpdateDataSelection();
string pFileName = "SubconOneLineList_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
string pSubConCodeLists = string.Empty;
string pJobCodeKey = string.Empty;
string pCountryCode = string.Empty;
string pWorkCategoryCode = string.Empty;
string pCapacityCode = string.Empty;
string pOperativeCountryCode = string.Empty;
string pNameAbbr = string.Empty;
string pAffiliates = string.Empty;
pSubConCodeLists = string.Join(",", DataSelection);
if (pSubConCodeLists == string.Empty)
{
GetSubconDatabaseFilter(out pSubConCodeLists, out pNameAbbr, out pJobCodeKey, out pCountryCode, out pOperativeCountryCode, out pWorkCategoryCode, out pAffiliates, out pCapacityCode);
}
string pGridFilter = (rgvSubcontractor.MasterTableView.FilterExpression == null ? string.Empty : rgvSubcontractor.MasterTableView.FilterExpression);
string pSortString = "";
if (rgvSubcontractor.MasterTableView.SortExpressions != null)
{
pSortString = ((rgvSubcontractor.MasterTableView.SortExpressions.GetSortString() == null) || (rgvSubcontractor.MasterTableView.SortExpressions.GetSortString() == string.Empty) ? pSortString : rgvSubcontractor.MasterTableView.SortExpressions.GetSortString());
}
pSortString = (pSortString == string.Empty ? "COMPANY_NAME ASC" : pSortString + ", COMPANY_NAME ASC");
DataTable pDTSubconOneLineList = mSubContractorBS.getRptSubContractorOneLineList(pSubConCodeLists, pNameAbbr, string.Empty, string.Empty, pJobCodeKey, pCountryCode, pOperativeCountryCode, pWorkCategoryCode, pAffiliates, pCapacityCode);
DataView pDVSubconOneLineList = new DataView(pDTSubconOneLineList);
if (pGridFilter != string.Empty)
{
pDVSubconOneLineList.RowFilter = pGridFilter;
}
pDVSubconOneLineList.Sort = pSortString;
pDTSubconOneLineList = pDVSubconOneLineList.ToTable();
pDTSubconOneLineList.TableName = "USP_RPT_SUBCON_ONE_LINE_LIST";
Process[] processList = Process.GetProcesses();
string path = Server.MapPath("~") + "\\SIS\\Template\\Download\\Subcon_Profile_List_Import_Template.xlsx";
//string targetPath = Convert.ToString(Session["App_Data_Path"]) + "EXPORT_OUTPUT";
string targetPath = Convert.ToString(Server.MapPath("~")) + "EXPORT_OUTPUT";
string destFile = System.IO.Path.Combine(targetPath, pFileName);
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
File.Copy(path, destFile, true);
object misValue = System.Reflection.Missing.Value;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(destFile, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];
xlWorkSheet.get_Range("A2", "AN" + xlWorkSheet.Rows.Count.ToString()).Clear();
object[,] objData = null;
int rowcount = pDTSubconOneLineList.Rows.Count;
objData = new Object[pDTSubconOneLineList.Rows.Count, pDTSubconOneLineList.Columns.Count];
for (int row = 0; row < pDTSubconOneLineList.Rows.Count; row++)
{
for(int column= 0; column < pDTSubconOneLineList.Columns.Count; column++)
{
objData[row, column] = pDTSubconOneLineList.Rows[row][column].ToString();
}
}
((Excel.Worksheet)xlWorkBook.Sheets[1]).Select(Type.Missing);
xlWorkBook.Save();
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet);
xlWorkSheet = null;
xlWorkBook = null;
xlApp = null;
GC.Collect();
string pMimeType = string.Empty;
string pEncoding = string.Empty;
string pExtension = string.Empty;
Response.Buffer = true;
Response.Clear();
Response.AppendCookie(new HttpCookie("fileDownloadToken", hdDownLoadToken.Value));
Response.ContentType = pMimeType;
Response.AddHeader("content-disposition", "attachment; filename=" + pFileName);
Response.Flush();
}
catch (Exception ex)
{
ErrorHelper.HandleError(ex);
}
You are not actually writing the data to the Sheet.
After your for loop filling objData, try:
Excel.Range targetRange = xlWorkSheet.get_Range("A2", "AN" + xlWorkSheet.Rows.Count.ToString());
targetRange.Value = objData;
I'm trying to create a excel from a datagrid with wpf, however when I format a column to just text it still converts some columns to what I presume to be a date conversion.
Excel.Range rg1 = (Excel.Range)xlWorkSheet.Cells[1, 3];
rg1.EntireColumn.NumberFormat = "text";
This is how the conversion of the column is set, but this results in Excel still formatting some fields to a date-ish value... If you look at the column foutcode you'll see what I mean.
results in:
I think what happens is that it automatically recognizes the value and sees if it fits a date format while I'm telling it to handle as just regular text! So does anyone have any idea on how to get rid of that? because the data is unusable because of this small error. Maybe use a more specific format than just text? however I can't seem to figure out how.
Also Convert a lot of rows into excel takes some quite a bit of time (4-5s for 1000 rows). Is there a way to make it go faster? All help is really appreciated.
public void ExportToExcel(List<Fouten> data)
{
try
{
if (data.Count > 0)
{
// Displays a SaveFileDialog so the user can save the Image
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel File|*.xls";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.FileName = "Data rapport";
// If the User Clicks the Save Button then the Module gets executed otherwise it skips the scope
if ((bool)saveFileDialog1.ShowDialog())
{
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp != null)
{
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int rowCount = 1;
xlWorkSheet.Cells[rowCount, 1] = "Datum";
xlWorkSheet.Cells[rowCount, 2] = "Tijd";
xlWorkSheet.Cells[rowCount, 3] = "Foutcode";
xlWorkSheet.Cells[rowCount, 4] = "Omschrijving";
xlWorkSheet.Cells[rowCount, 5] = "Module";
xlWorkSheet.Cells[rowCount, 6] = "TreinId";
rowCount++;
Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[1, 2];
rg.EntireColumn.NumberFormat = "hh:mm:ss.000";
Excel.Range rg1 = (Excel.Range)xlWorkSheet.Cells[1, 3];
rg1.EntireColumn.NumberFormat = "text";
foreach (Fouten item in data)
{
string[] moduleNaam = item.Module.Split('_');
xlWorkSheet.Cells[rowCount, 1] = item.Datum;
xlWorkSheet.Cells[rowCount, 2] = item.Time.ToString();
xlWorkSheet.Cells[rowCount, 3] = item.FoutCode;
xlWorkSheet.Cells[rowCount, 4] = item.Omschrijving;
xlWorkSheet.Cells[rowCount, 5] = moduleNaam[0].ToUpper();
xlWorkSheet.Cells[rowCount, 6] = item.TreinId;
rowCount++;
}
xlWorkSheet.Columns.AutoFit();
// If the file name is not an empty string open it for saving.
if (!String.IsNullOrEmpty(saveFileDialog1.FileName.ToString()) && !string.IsNullOrWhiteSpace(saveFileDialog1.FileName.ToString()))
{
xlWorkBook.SaveAs(saveFileDialog1.FileName, Excel.XlFileFormat.xlWorkbookNormal);
xlWorkBook.Close(true);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel File Exported Successfully", "Export Engine");
}
}
}
}
else
{
MessageBox.Show("Nothing to Export", "Export Engine");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The Range.NumberFormat property for Text is an 'at' symbol (e.g. capital 2 or #), not the word Text.
rg1.EntireColumn.NumberFormat = "#";
More at Number Format Codes.
I want to name each column in the first row of the excel sheet, I get an exception on the first line of naming the columns. Please advise?
Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = xla.Workbooks.Add(Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)xla.ActiveSheet;
int i = 2;
int j = 1;
if (comboBox1.Text == "Brickcom")
{
try
{
ws.Rows[j, 1] = "Category";
ws.Rows[j, 2] = "Part Number";
ws.Rows[j, 3] = "TradePrice";
ws.Rows[j, 4] = "Product";
ws.Rows[j, 5] = "Resolution";
ws.Rows[j, 6] = "Included Accessories";
ws.Rows[j, 7] = "Major Acc Price";
foreach (ListViewItem comp in listView1.Items)
{
ws.Cells[i, j] = comp.Text.ToString();
foreach (ListViewItem.ListViewSubItem drv in comp.SubItems)
{
ws.Cells[i, j] = drv.Text.ToString();
j++;
}
j = 1;
i++;
}
xla.Visible = true;
}
catch
{
MessageBox.Show("Export did not work");
}
}
Try this:
ws.Cells[j, 1] = "Category";
ws.Cells[j, 2] = "Part Number";
ws.Cells[j, 3] = "TradePrice";
...
i would use stream writer :
SaveFileDialog savefile = new SaveFileDialog();
savefile.Filter = "CSV|*.csv";
savefile.RestoreDirectory = true;
savefile.ShowDialog();
string filename = savefile.FileName;
if (filename != "")
{
StreamWriter ofile = new StreamWriter(filename);
ofile.WriteLine("Category, Part Number, TradePrice, ..."); //just separate using a comma ,
//your complete writings here
ofile.Close(); //close the streamwriter and you're done
}
good luck
My code is as follows
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(file);
Excel.Worksheet xlSheet = xlWorkbook.Sheets[1]; // get first sheet
Excel.Range xlRange = xlSheet.UsedRange;
These are the only variables used in my function
foreach (Excel.Worksheet XLws in xlWorkbook.Worksheets)
{
// do some stuff
xlApp.UserControl = false;
if (xlRange != null)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlRange);
if (xlSheet != null)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlSheet);
if (xlWorkbook != null)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbook);
xlRange = null;
xlSheet = null;
xlWorkbook = null;
xlApp.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp);
}
But still I get EXCEL.EXE in Task Manager
Please help?
Kill the excel process which has empty value for MainWindowTitle. Below is an example source code.
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Salary";
//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").VerticalAlignment =
Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Create an array to multiple values at once.
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[4, 1] = "Johnson";
//Fill A2:B6 with an array of values (First and Last Names).
oSheet.get_Range("A2", "B6").Value2 = saNames;
//Fill C2:C6 with a relative formula (=A2 & " " & B2).
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
//Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.get_Range("D2", "D6");
oRng.Formula = "=RAND()*100000";
oRng.NumberFormat = "$0.00";
//AutoFit columns A:D.
oRng = oSheet.get_Range("A1", "D1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("c:\\test505.xls", 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);
oWB.Close(null, null, null);
oXL.Quit(); //MainWindowTitle will become empty afer being close
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oXL);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oWB);
Process[] excelProcesses = Process.GetProcessesByName("excel");
foreach (Process p in excelProcesses)
{
if (string.IsNullOrEmpty(p.MainWindowTitle)) // use MainWindowTitle to distinguish this excel process with other excel processes
{
p.Kill();
}
}
}
catch (Exception ex2)
{
}
You've got an implicit object left open. Try this
Excel.Application xlApp = new Excel.Application();
Excel.Workbooks xlWorkbooks = xlApp.Workbooks;
Excel.Workbook xlWorkbook = xlWorkbooks.Open(file);
....
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbooks);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbook);
....
OK... I hope this helps... it took me forever to tweak this to get it to work just so...
Here is my entire function (VB -- but the C# code for the tricky stuff is in there (thanks to too many other stackoverflow giants who helped me get this far!)
Private Function ImportWorksFile() As Integer
Dim EndofSheet As Boolean
Dim BlankRowCounter As Integer
Dim rr As RowResult
Dim SecCount As Integer = 0
Dim SecRow As SecurityRow
Dim uf As New UtilFunctions
'If this has already been run, the instance of the excel object would have been 'killed' and needs to be reinstantiated
If blnExcelProcessKilled Then 'Global boolean var
xlApp = New Excel.Application()
blnExcelProcessKilled = False
End If
Dim excelProcess(0) As Process
excelProcess = Process.GetProcessesByName("excel")
Dim tmp As Excel.Workbooks
Try
tmp = xlApp.Workbooks
xlWorkBook = tmp.Open(WorkingFileName)
Catch ex As Exception
MessageBox.Show("There was a problem opening the workbook - please try again", CurAFLApp.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return 0
End Try
Using dc As New AFLData(CurAFLApp, True)
Dim cmd As SqlCommand = DefineCommand()
cmd.CommandType = CommandType.StoredProcedure
For Each ws As Excel.Worksheet In xlWorkBook.Worksheets
Dim row As Integer = 1
EndofSheet = False
BlankRowCounter = 0
If ImpCols.ContainsKey(ws.Name) Then
SecRow = New SecurityRow(ImpCols(ws.Name))
Do Until EndofSheet
Try
SecRow.NewRow(ws.Rows(row))
rr = SecRow.IsValidRow
If rr = RowResult.Valid Then
' read this row and process
With cmd
.Parameters("#AcctDate").Value = FileDate
.Parameters("#NewSub").Value = SecRow.GetStrCell("newsub")
RunProcedure(cmd)
End With
SecCount += 1
BlankRowCounter = 0
Else
BlankRowCounter += rr
End If
Catch ex As Exception
MessageBox.Show("There was a problem with row: " & row & " in workbook " & ws.Name)
End Try
' if we've counted 50 blank A column values in a row, we're done.
If BlankRowCounter <= -50 Then
EndofSheet = True
End If
row += 1
Loop
End If
Next
End Using
Try
xlWorkBook.Close(SaveChanges:=False)
xlApp.Workbooks.Close()
xlApp.Quit()
'// And now kill the process. C# Version (for reference)
'if (processID != 0)
'{
' Process process = Process.GetProcessById(processID);
' process.Kill();
'}
' Reversed the order of release per http://stackoverflow.com/questions/12916137/best-way-to-release-excel-interop-com-object
Catch ex As Exception
MessageBox.Show("There was a problem CLOSING the workbook - Please double check that the data was imported correctly. ", CurAFLApp.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return 0
Finally
releaseObject(tmp)
releaseObject(xlWorkBook)
releaseObject(xlApp)
If Not excelProcess(0).CloseMainWindow() Then
excelProcess(0).Kill()
blnExcelProcessKilled = True
End If
End Try
Return SecCount
End Function
Public Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
'Not sure if the following line helps or hinders -- seems to lock things up once in a while
'GC.WaitForPendingFinalizers()
End Try
End Sub
Try :
xlWorkbook.Close(false); // if you Workbook should not be saved
instead of :
if (xlWorkbook != null)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbook);
xlWorkbook = null;