so currently my code below generates a string and adds it to a list for each image file in a directory, then after its does adding to the list, it opens an excel file, appends the list, and formats it. Currently my problem is that my excel line is selecting the entireColumn and pasting the list, how can I get it to recognize how many strings are in the list and only append that many to the excel sheet.
//Fill A2:B6 with an array of values .
oRng = oSheet.get_Range("C2");
oRng.EntireColumn.Value2 = checkInformation.ToArray();
Here is my whole project
class Program
{
[STAThread]
static void Main(string[] args)
{
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;
Console.WriteLine("Initializing Check Parser Menu.....");
string dataPath = #"C:\Users\User\Desktop\Tesseract\Tesseract\tessdata";
string[] filePaths = Directory.GetFiles(#"C:\Users\User\Desktop\Tesseract\Tesseract\Check_Images", "*.png");
string checkData = "";
int checkCounter = 0;
List<string> checkInformation = new List<string>();
foreach (string filePath in filePaths)
{
checkCounter++;
Console.WriteLine("Initializing Check Parser... on Check: " + checkCounter);
using (TesseractEngine ocr = new TesseractEngine(dataPath, "eng", EngineMode.TesseractOnly))
{
using (Pix p = Pix.LoadFromFile(filePath))
{
using (Pix img = p.Scale(2, 3))
{
using (var page = ocr.Process(img))
{
string text = page.GetText();
if (text.Contains("Claim ID"))
{
int indexOfNone = text.IndexOf("NONE");
int indexOfClaimId = text.IndexOf("Claim ID");
int difference = indexOfClaimId - indexOfNone;
var dollarData = text.Substring(indexOfNone, difference);
int startingPoint = indexOfNone + (dollarData.Length - 6);
var dollarAmount = text.Substring(startingPoint, 6);
var claimIdData = text.Substring(indexOfClaimId, 14);
var claimInfoOutput = claimIdData + " Check Amount: " + dollarAmount;
Console.WriteLine(claimInfoOutput);
checkInformation.Add(claimInfoOutput);
}
else
{
Console.WriteLine("You will need to locate this check, there was an issue parsing " + "\n" + filePath);
Console.WriteLine("Press any Key to continue");
Console.ReadKey();
}
}
}
}
}
}
Console.WriteLine("Writing Data to Excel File... DONT TaCH");
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. //Format A1:B1 as bold, vertical alignment = center.
oSheet.Cells[1, 1] = "Claim ID";
oSheet.Cells[1, 2] = "Check Amount";
oSheet.get_Range("A1", "B1").Font.Bold = true;
oSheet.get_Range("A1", "B1").VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Create an array to multiple values at once.
//Fill A2:B6 with an array of values .
oRng = oSheet.get_Range("C2");
oRng.Value2 = checkInformation.ToArray();
//oSheet.get_Range("A2", "B6").Value2 = checkInformation.ToArray();
//Fill A2 with a formula(=MID(C2,9,5)
oRng = oSheet.get_Range("A2", "A50");
oRng.Formula = "=MID(C2,9,5)";
//Fill B2 with a =RIGHT(C2,6)
oRng = oSheet.get_Range("B2", "B50");
oRng.Formula = "=RIGHT(C2,6)";
//AutoFit columns A:C.
oRng = oSheet.get_Range("A1", "C1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("C:\\Users\\User\\Desktop\\Tesseract\\Tesseract\\excel\\checkdata.xlsx", 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();
;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Okay I solved it guys sorry to bug you but heres what I did.
//Fill A2:B6 with an array of values .
string cellName;
int counter = 2;
foreach (var check in checkInformation)
{
cellName = "C" + counter.ToString();
oRng = oSheet.get_Range(cellName, cellName);
oRng.Value2 = check.ToString();
++counter;
}
and basically i just need to say for each item in my list this is the first cell name append the value.tostring
Related
I want to export all my DataGridViews in one Excell document.
For every DataGridView there shoud be a own sheet in the Excell File.
But with my code i only recive the Error: System.Runtime.InteropServices.COMException: HRESULT: 0x800A03EC"
I think there is something wrong with my parameters.
private void exportToExcellButton_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileD = new SaveFileDialog();
string fileName = truckListBox.SelectedItem.ToString() + "__" + DateTime.Now.ToShortDateString();
saveFileD.InitialDirectory = #"C:/TML/";
saveFileD.FileName = fileName;
if (!Directory.Exists(#"C:/TML/"))
Directory.CreateDirectory(#"C:/TML/");
List<DataGridView> dataGridViews = getAllDataGridViews();
Microsoft.Office.Interop.Excel.Application app;
Microsoft.Office.Interop.Excel.Workbook book;
Microsoft.Office.Interop.Excel.Worksheet sheet;
app = new Excel.Application();
app.Visible = true;
book = app.Workbooks.Add(System.Reflection.Missing.Value);
foreach (var grid in dataGridViews)
{
int count = book.Worksheets.Count;
sheet = (Worksheet)book.Sheets.Add(Type.Missing, book.Worksheets[count], Type.Missing, Type.Missing);
sheet.Name = grid.Name.ToString().Remove(0, 13);
int cMin = 0, rMin = 0;
int c = cMin, r = rMin;
// Set Headers
foreach (DataGridViewColumn column in grid.Columns)
{
//Here appears the Error: System.Runtime.InteropServices.COMException: HRESULT: 0x800A03EC"
sheet.Cells[r, c] = column.HeaderText;
c++;
}
sheet.Range[sheet.Cells[r, cMin], sheet.Cells[r, c]].Font.Bold = true;
sheet.Range[sheet.Cells[r, cMin], sheet.Cells[r, c]].VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Set Rows
foreach (DataGridViewRow row in grid.Rows)
{
r++;
c = cMin;
// Set Cells
foreach (DataGridViewCell item in row.Cells)
{
sheet.Cells[r, c++] = item.Value;
}
}
}
book.Save();
book.Close();
app.Quit();
}
Spended allready days into it and cant get it work.
Thx for your Help!
EDIT: Fixed one error to get to the new one.
There are a few problems you may have with the posted code. Therefore, I will break them down.
For starters, it appears you are using a SaveFileDialog however I do not see where it is being used. The code sets the InitalDirectory and FileName, but it is never used. This is not that important as a dialog is not really needed, however the way the code is getting the file name is going to have some problems. The line of code…
string fileName = truckListBox.SelectedItem.ToString() + "__" + DateTime.Now.ToShortDateString();
is going to have problems if you try to save the file name because the string returned from DateTime.Now.ToShortDateString() is going to be in a format like “2019\11\26”… Obviously the “\” characters are going to be interpreted as a path (folder) and will most likely fail when the code tries to save the file. Creating a method that returns a string that uses some other character should be easy to fix this.
Next is the fact that Excel files are NOT zero based on their rows and columns. Therefore, setting the initial Excel row column variables (int c = 0, r = 0;) will fail on the first try. These values should be one (1).
Another problem is on the line…
book.Save();
Is most likely going to save the file to the users “Documents” folder using the file name of “Book1.xlsx.” When saving the file you need to supply the complete path and file name which as stated earlier does not appear to be used.
Lastly, anytime you use “COM” objects such as Excel apps, workbooks and worksheets, it is very important for the code to “RELEASE” the com objects your code creates before you exit the program. In the current posted code, it is highly likely that there are lingering “Excel” resources still running. Therefore, to avoid leaking resources, it is important for your code to release the com objects it creates.
In my example below the code to release the resources is in the finally clause of the try/catch/finally statement.
private void button1_Click(object sender, EventArgs e) {
//SaveFileDialog saveFileD = new SaveFileDialog();
//string fileName = truckListBox.SelectedItem.ToString() + "__" + DateTime.Now.ToShortDateString();
string fileName = #"C:\Users\John\Desktop\Grr\TestExcelFile" + "__" + DateTime.Now.Year + "_" + DateTime.Now.Month;
//saveFileD.InitialDirectory = #"C:\Users\John\Desktop\Grr\";
//saveFileD.FileName = fileName;
//if (!Directory.Exists(#"C:/TML/"))
// Directory.CreateDirectory(#"C:/TML/");
//List<DataGridView> dataGridViews = getAllDataGridViews();
List<DataGridView> dataGridViews = getGrids();
Microsoft.Office.Interop.Excel.Application app = null;
Microsoft.Office.Interop.Excel.Workbook book = null;
Microsoft.Office.Interop.Excel.Worksheet sheet = null;
app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
book = app.Workbooks.Add(System.Reflection.Missing.Value);
try {
foreach (var grid in dataGridViews) {
int count = book.Worksheets.Count;
//sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.Sheets.Add(Type.Missing, book.Worksheets[count], Type.Missing, Type.Missing);
sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.Worksheets.Add();
//sheet.Name = grid.Name.ToString().Remove(0, 13);
sheet.Name = grid.Name.ToString();
int cMin = 1, rMin = 1;
int c = cMin, r = rMin;
// Set Headers
foreach (DataGridViewColumn column in grid.Columns) {
//Here appears the Error: System.Runtime.InteropServices.COMException: HRESULT: 0x800A03EC"
sheet.Cells[r, c] = column.HeaderText;
c++;
}
sheet.Range[sheet.Cells[r, cMin], sheet.Cells[r, c]].Font.Bold = true;
sheet.Range[sheet.Cells[r, cMin], sheet.Cells[r, c]].VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Set Rows
foreach (DataGridViewRow row in grid.Rows) {
r++;
c = cMin;
// Set Cells
foreach (DataGridViewCell item in row.Cells) {
sheet.Cells[r, c++] = item.Value;
}
}
}
book.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing);
book.Close();
app.Quit();
}
catch (Exception ex) {
MessageBox.Show("Error writing to excel: " + ex.Message);
}
finally {
if (sheet != null)
Marshal.ReleaseComObject(sheet);
if (book != null)
Marshal.ReleaseComObject(book);
if (app != null)
Marshal.ReleaseComObject(app);
}
}
Hope this helps.
Simply Make a method and pass DataGridView
using Excel = Microsoft.Office.Interop.Excel;
public void ete(DataGridView dgv)//ExportToExcel
{
// Creating a Excel object.
Excel._Application excel = new Excel.Application();
Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
Excel._Worksheet worksheet = null;
excel.Columns.ColumnWidth = 20;
try
{
worksheet = workbook.ActiveSheet;
worksheet.Name = "ExportedFromDatGrid";
int cellRowIndex = 1;
int cellColumnIndex = 1;
//Loop through each row and read value from each column.
for (int i = -1; i < dgv.Rows.Count; i++)
{
for (int j = 0; j < dgv.Columns.Count; j++)
{
// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
if (cellRowIndex == 1)
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dgv.Columns[j].HeaderText;
}
else
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dgv.Rows[i].Cells[j].Value.ToString();
}
cellColumnIndex++;
}
cellColumnIndex = 1;
cellRowIndex++;
}
//Getting the location and file name of the excel to save from user.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
saveDialog.FilterIndex = 2;
if (saveDialog.ShowDialog() == DialogResult.OK)
{
workbook.SaveAs(saveDialog.FileName.ToString());
MessageBox.Show("Export Successful");
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
excel.Quit();
workbook = null;
excel = null;
}
}
Now Call Method
ete(datagridview1);
I'm generating an excel file in C# and excel file is format is as follows.
And Columns From C1 will be dynamic since there can be several dates.
And what I need to do is only allow editing for rows with Ctype
YYY
Is there any way to identify rows with Ctype = YYY
The code I use to generate excel is as follows
public string ExcelGenerator()
{
DataTable dt = GetDataTable();
var fileName = "ExcelFile";
var excelApp = new Application();
var workbooks = excelApp.Workbooks;
var excelWorkBook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
var sheets = excelWorkBook.Sheets;
var excelWorkSheet = sheets[1];
excelWorkSheet.Name = "ExcelFile";
int iCol = 1;
// Add column headings...
foreach (DataColumn c in dt.Columns)
{
excelWorkSheet.Cells[1, iCol] = c.ColumnName; ;
((Range)excelWorkSheet.Cells[1, iCol]).Interior.Color = ColorTranslator.ToOle(Color.DarkGray);
iCol++;
}
// for each row of data...
for (int j = 0; j < dt.Rows.Count; j++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
excelWorkSheet.Cells[j + 2, k + 1] = dt.Rows[j].ItemArray[k].ToString();
}
}
string fullpath = Path.Combine(excelPath, fileName);
if (File.Exists(fullpath))
{
try
{
File.Delete(fullpath);
}
catch (IOException e)
{
Console.Write(e.Message);
}
}
excelApp.DisplayAlerts = false;
excelWorkBook.SaveAs(fullpath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, true, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
excelWorkBook.Close(false, Type.Missing, Type.Missing);
excelApp.Quit();
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(excelWorkSheet);
Marshal.ReleaseComObject(sheets);
Marshal.ReleaseComObject(excelWorkBook);
Marshal.ReleaseComObject(excelApp);
excelWorkSheet = null;
excelWorkBook = null;
excelApp = null;
workbooks = null;
GC.WaitForPendingFinalizers();
GC.Collect();
return fileName;
}
Excel.Office.Interop don't allow range unprotection by programmatically.
For more information, you may visit this website.
https://msdn.microsoft.com/en-us/library/dkcs53f3.aspx
But if you use EPPlus library, you can do like Excel users.
if you allow selective editable column, excel requires sheet protection = true and some unprotected range.
(using EPPlus)
excelWorkSheet.Protection.IsProtected = true;
excelWorkSheet.ProtectedRanges.Add("editable", new ExcelAddress("B"));
hi i exported gridview data into excel but unfortunately the data inside the exported file was different,supposed to be a datatable.
Below is my script in export button, can you tell me what is wrong in my script. I am new in ASP.net thanks
try
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
int StartCol = 1;
int StartRow = 1;
int j = 0, i = 0;
//Write Headers
for (j = 0; j < GridView1.Columns.Count; j++)
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j];
myRange.Value = GridView1.Columns[j].HeaderText;
}
StartRow++;
//Write datagridview content
for (i = 0; i < GridView1.Rows.Count; i++)
{
for (j = 0; j < GridView1.Columns.Count; j++)
{
try
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + i, StartCol + j];
myRange.Value2 = GridView1.Rows[i].Cells[j].Text + ";" == null ? "" : GridView1.Rows[i].Cells[j].Text + ";";
}
catch
{
GridView1.DataBind();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
// ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
// "alertMessage",
// "alert(ex.ToString());", true);
}
You can export datagridview data to an excel using the below method:
public void ExportToExcel(DataGridView dgv)
{
try
{
dgv.SelectAll();
dgv.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
DataObject doj = dgv.GetClipboardContent();
Clipboard.SetDataObject(doj);
dgv.ClearSelection();
Microsoft.Office.Interop.Excel.Application exap = new Microsoft.Office.Interop.Excel.Application();
exap.Visible = true;
Workbook exwb = (Workbook)exap.Workbooks.Add();
Worksheet exws = (Worksheet)exwb.Sheets["Sheet1"];
exws.Paste();
Clipboard.Clear();
Range cell1 = exws.Cells[1, 2];
Range cell2 = exws.Cells[dgv.Rows.Count + 1, dgv.ColumnCount + 1];
Range cell3 = exws.Cells[1, dgv.ColumnCount + 1];
Range range = exws.get_Range(cell1, cell2);
Range colorrange = exws.get_Range(cell1, cell3);
range.Borders.Weight = XlBorderWeight.xlThin;
colorrange.Interior.Color = System.Drawing.Color.SteelBlue;
colorrange.Font.Color = System.Drawing.Color.White;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel File 2010 (*.xlsx)|*.xlsx|Excel File 2003 (*.xls)|*.xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
exwb.SaveAs(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
}
catch(System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This method copies all data in the datagridview & pastes it in an excel.You ofcourse need to add a reference to Microsoft.Office.Interop.Excel.
Alternately if you wish to export a datatable to excel you can try below method:
public void ExporttoExcel(System.Data.DataTable dtbl)
{
StringBuilder Output = new StringBuilder();
//The first "line" will be the Headers.
for (int i = 0; i < dtbl.Columns.Count; i++)
{
Output.Append(dtbl.Columns[i].ColumnName + "\t");
}
Output.Append("\n");
//Generate Cell Value Data
foreach (DataRow Row in dtbl.Rows)
{
if (Row.RowState != DataRowState.Deleted)
{
for (int i = 0; i < Row.ItemArray.Length; i++)
{
//Handling the last cell of the line.
if (i == (Row.ItemArray.Length - 1))
{
Output.Append(Row.ItemArray[i].ToString() + "\n");
}
else
{
Output.Append(Row.ItemArray[i].ToString() + "\t");
}
}
}
}
Clipboard.SetText(Output.ToString());
Microsoft.Office.Interop.Excel.Application exap = new Microsoft.Office.Interop.Excel.Application();
exap.Visible = true;
Workbook exwb = (Workbook)exap.Workbooks.Add();
Worksheet exws = (Worksheet)exwb.Sheets["Sheet1"];
exws.Paste();
Clipboard.Clear();
Range cell1 = exws.Cells[1, 1];
Range cell2 = exws.Cells[dtbl.Rows.Count, dtbl.Columns.Count];
Range cell3 = exws.Cells[1, dtbl.Columns.Count];
Range range = exws.get_Range(cell1, cell2);
Range colorrange = exws.get_Range(cell1, cell3);
range.Borders.Weight = XlBorderWeight.xlThin;
colorrange.Interior.Color = System.Drawing.Color.SteelBlue;
colorrange.Font.Color = System.Drawing.Color.White;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel File 2010 (*.xlsx)|*.xlsx|Excel File 2003 (*.xls)|*.xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
exwb.SaveAs(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
}
Please check if these methods help.
use Text.Replace(" ", "")
myRange.Value2 = GridView1.Rows[i].Cells[j].Text.Replace(" ", "") + ";" == null ? "" : GridView1.Rows[i].Cells[j].Text + ";";
in markup
<asp:BoundField DataField="EmployeeName" HeaderText="Name" NullDisplayText=" "/>
I suspect your GridView Bind fails. Below is the method which you can try.
private void ExportToExcel()
{
//First fetch all records from grid to dataset
DataSet dset = new DataSet();
dset.Tables.Add();
//First Add Columns from gridview to excel
for (int i = 0; i < gridView.Columns.Count; i++) //GridView is id of gridview
{
dset.Tables[0].Columns.Add(gridView.Columns[i].HeaderText);
}
//add rows to the table
System.Data.DataRow dr1;
for (int i = 0; i < gridView.Rows.Count; i++)
{
dr1 = dset.Tables[0].NewRow(); //For Example There are only 3 columns into gridview
System.Web.UI.WebControls.Label lblCCName =
(System.Web.UI.WebControls.Label)gridView.Rows[i].Cells[0].FindControl("lblCCName");
System.Web.UI.WebControls.Label lblItemName =
(System.Web.UI.WebControls.Label)gridView.Rows[i].Cells[0].FindControl("lblItemName");
System.Web.UI.WebControls.Label lblItemCode =
(System.Web.UI.WebControls.Label)gridView.Rows[i].Cells[0].FindControl("lblItemCode");
dr1[0] = lblCCName.Text.ToString();
dr1[1] = lblItemName.Text.ToString();
dr1[2] = lblItemCode.Text.ToString();
dset.Tables[0].Rows.Add(dr1);
}
//below code is export dset to excel
ApplicationClass excel = new ApplicationClass();
Workbook wBook;
Worksheet wSheet;
wBook = excel.Workbooks.Add(System.Reflection.Missing.Value);
wSheet = (Worksheet)wBook.ActiveSheet;
System.Data.DataTable dt = dset.Tables[0];
System.Data.DataColumn dc = new DataColumn();
int colIndex = 0;
int rowIndex = 4;
foreach (DataColumn dcol in dt.Columns)
{
colIndex = colIndex + 1;
excel.Cells[5, colIndex] = dcol.ColumnName;
}
foreach (DataRow drow in dt.Rows)
{
rowIndex = rowIndex + 1;
colIndex = 0;
foreach (DataColumn dcol in dt.Columns)
{
colIndex = colIndex + 1;
excel.Cells[rowIndex + 1, colIndex] = drow[dcol.ColumnName];
}
}
wSheet.Columns.AutoFit();
// Server File Path Where you want to save excel file.
String strFileName = Server.MapPath("~\\Images\\StockStatement.xls");
Boolean blnFileOpen = false;
try
{
System.IO.FileStream fileTemp = File.OpenWrite(strFileName);
fileTemp.Close();
}
catch
{
blnFileOpen = false;
}
if (System.IO.File.Exists(strFileName))
//It checks if file exists then it delete that file.
{
System.IO.File.Delete(strFileName);
}
}
In the Button_Click() event, call this function.
Hi this is were i came up after long journey, i used the Aspose method on Exporting Gridview in Excel, it's simple yet so powerfull! hope this will help,
Code behind Export_button:
//Instantiate a new workbook
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
//Get the first worksheet in the workbook
Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];
//Import data from GridView control to fill the worksheet
worksheet.Cells.ImportGridView(GridView1, 0, 0, new Aspose.Cells.ImportTableOptions() { IsFieldNameShown = true });
worksheet.AutoFitColumns();
//Send result to client in XLS format
workbook.Save(this.Response, "export.xls", ContentDisposition.Attachment, new Aspose.Cells.XlsSaveOptions());
Hi i try to get better with the c# excel stuff. Right now i try to select some values from an existing excelsheet. For Example: From B4 to C16. So i can replace the values with something else but i dont get it to work.
This is my little method:
public void writeExcelFile()
{
string path = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
oXL = new Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Excel.Worksheet)mWorkSheets.get_Item(1);
//Excel.Range range = mWSheet1.UsedRange;
//int colCount = range.Columns.Count;
//int rowCount = range.Rows.Count;
int countRows = mWSheet1.UsedRange.Rows.Count;
int countColumns = mWSheet1.UsedRange.Columns.Count;
object[,] data = mWSheet1.Range[mWSheet1.Cells[1, 1], mWSheet1.Cells[countRows, countColumns]].Cells.Value2;
for (int index = 1; index < 15; index++)
{
mWSheet1.Cells[countRows + index, 1] = countRows + index;
mWSheet1.Cells[countRows + index, 2] = "test" + index;
}
//Excel.Worksheet sheet = workbook.ActiveSheet;
//Excel.Range rng = (Excel.Range)sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3, 3]);
mWorkBook.SaveAs(path, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive,Missing.Value, Missing.Value, Missing.Value,Missing.Value, Missing.Value);
mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
mWSheet1 = null;
mWorkBook = null;
oXL.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
I tried it with get_range but i get an exception that this is not aviable.
It has something to do with the Microsoft.Office.Interop libary 14. Then i tried it with object[,] but the only thing i got to work is that after all used cells to insert test but not to select anything. So any help would be great.
Thanks for your Time and sorry for my english.
EDIT: At least the read process works now and i loop trough a selected range.
Here is the working code:
public void writeExcelFile()
{
String inputFile = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
Excel.Application oXL = new Excel.Application();
#if DEBUG
oXL.Visible = true;
oXL.DisplayAlerts = true;
#else
oXL.Visible = false;
oXL.DisplayAlerts = false;
#endif
//Open the Excel File
Excel.Workbook oWB = oXL.Workbooks.Open(inputFile);
String SheetName = "Gesamt";
Excel._Worksheet oSheet = oWB.Sheets[SheetName];
String start_range = "B4";
String end_range = "R81";
Object[,] values = oSheet.get_Range(start_range, end_range).Value2;
int t = values.GetLength(0);
for (int i = 1; i <= values.GetLength(0); i++)
{
String val = values[i, 1].ToString();
}
oXL.Quit();
}
After many tries i finnaly got a working solution where i can select any cells i want. Maby there are better ways but for me it works as expected.
the code:
public void writeExcelFile()
{
try
{
String inputFile = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
Excel.Application oXL = new Excel.Application();
#if DEBUG
oXL.Visible = true;
oXL.DisplayAlerts = true;
#else
oXL.Visible = false;
oXL.DisplayAlerts = false;
#endif
//Open a Excel File
Excel.Workbook oWB = oXL.Workbooks.Add(inputFile);
Excel._Worksheet oSheet = oWB.ActiveSheet;
List<String> Name = new List<String>();
List<Double> Percentage = new List<Double>();
Name.Add("Anil");
Name.Add("Vikas");
Name.Add("Ashwini");
Name.Add("Tobias");
Name.Add("Stuti");
Name.Add("Raghavendra");
Name.Add("Chithra");
Name.Add("Glen");
Name.Add("Darren");
Name.Add("Michael");
Percentage.Add(78.5);
Percentage.Add(65.3);
Percentage.Add(56);
Percentage.Add(56);
Percentage.Add(97);
Percentage.Add(89);
Percentage.Add(85);
Percentage.Add(76);
Percentage.Add(78);
Percentage.Add(89);
oSheet.Cells[1, 1] = "Name";
oSheet.Cells[1, 2] = "Percentage(%)"; // Here 1 is the rowIndex and 2 is the columnIndex.
//Enter the Header data in Column A
int i = 0;
for (i = 0; i < Name.Count; i++)
{
oSheet.Cells[i + 2, 1] = Name[i];
}
//Enter the Percentage data in Column B
for (i = 0; i < Percentage.Count; i++)
{
oSheet.Cells[i + 2, 2] = Percentage[i];
}
oSheet.Cells[Name.Count + 3, 1] = "AVERAGE";
//Obtain the Average of the Percentage Data
string currentFormula = "=AVERAGE(B2:" + "B" + Convert.ToString(Percentage.Count + 1) + ")";
oSheet.Cells[Percentage.Count + 3, 2].Formula = currentFormula;
//Format the Header row to make it Bold and blue
oSheet.get_Range("A1", "B1").Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.AliceBlue);
oSheet.get_Range("A1", "B1").Font.Bold = true;
//Set the column widthe of Column A and Column B to 20
oSheet.get_Range("A1", "B12").ColumnWidth = 20;
//String ReportFile = #"D:\Excel\Output.xls";
oWB.SaveAs(inputFile, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,
Type.Missing, Type.Missing,
false,
false,
Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
oXL.Quit();
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);
oSheet = null;
oWB = null;
oXL = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);
}
catch (Exception ex)
{
String errorMessage = "Error reading the Excel file : " + ex.Message;
MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
This is not my own code its from a blog: the blog where i got it just edited so it works for me.
How do I access the string value in a cell in an Excel worksheet?
string cellInfo = (string)w.Cells[3, 3];
I want the string value in the 3rd row, 3rd column, C3
Excel.Application excel = new Excel.Application();
Excel.Workbook workBook = excel.Workbooks.Open(string.Format(#"{0}\{1}", Directory.GetCurrentDirectory(), excelFilename),
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
List<Excel.Worksheet> result = excel.Worksheets.Cast<Excel.Worksheet>().Where(w => !exclude.Contains(w.Name)).ToList();
result.ForEach(w => {
Excel.Range objRange = w.get_Range("C3", "C3");
string colLengthStr = objRange.Value2;
}
There are many answers on SO about how to get data from Excel using c#. But you will need to do something similar to this:
Excel.Range objRange = (Excel.Range)objSheet.Cells[1,1];
strData = objRange.get_Value(Missing.Value).ToString();
How to read data of an Excel file using C#?
Resources for learning c# Excel interop
Or
C# Excel Interop
Or Even
How to automate Excel from C#.NET
Code from the automate Excel from c#.net, which includes reading/writing to cells:
private void button1_Click(object sender, System.EventArgs e)
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
try
{
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
oSheet = (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 =
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[ 1, 1] = "Brown";
saNames[ 2, 0] = "Sue";
saNames[ 2, 1] = "Thomas";
saNames[ 3, 0] = "Jane";
saNames[ 3, 1] = "Jones";
saNames[ 4, 0] = "Adam";
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();
//Manipulate a variable number of columns for Quarterly Sales Data.
DisplayQuarterlySales(oSheet);
//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
oXL.Visible = true;
oXL.UserControl = true;
}
catch( Exception theException )
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat( errorMessage, theException.Message );
errorMessage = String.Concat( errorMessage, " Line: " );
errorMessage = String.Concat( errorMessage, theException.Source );
MessageBox.Show( errorMessage, "Error" );
}
}
private void DisplayQuarterlySales(Excel._Worksheet oWS)
{
Excel._Workbook oWB;
Excel.Series oSeries;
Excel.Range oResizeRange;
Excel._Chart oChart;
String sMsg;
int iNumQtrs;
//Determine how many quarters to display data for.
for( iNumQtrs = 4; iNumQtrs >= 2; iNumQtrs--)
{
sMsg = "Enter sales data for ";
sMsg = String.Concat( sMsg, iNumQtrs );
sMsg = String.Concat( sMsg, " quarter(s)?");
DialogResult iRet = MessageBox.Show( sMsg, "Quarterly Sales?",
MessageBoxButtons.YesNo );
if (iRet == DialogResult.Yes)
break;
}
sMsg = "Displaying data for ";
sMsg = String.Concat( sMsg, iNumQtrs );
sMsg = String.Concat( sMsg, " quarter(s)." );
MessageBox.Show( sMsg, "Quarterly Sales" );
//Starting at E1, fill headers for the number of columns selected.
oResizeRange = oWS.get_Range("E1", "E1").get_Resize( Missing.Value, iNumQtrs);
oResizeRange.Formula = "=\"Q\" & COLUMN()-4 & CHAR(10) & \"Sales\"";
//Change the Orientation and WrapText properties for the headers.
oResizeRange.Orientation = 38;
oResizeRange.WrapText = true;
//Fill the interior color of the headers.
oResizeRange.Interior.ColorIndex = 36;
//Fill the columns with a formula and apply a number format.
oResizeRange = oWS.get_Range("E2", "E6").get_Resize( Missing.Value, iNumQtrs);
oResizeRange.Formula = "=RAND()*100";
oResizeRange.NumberFormat = "$0.00";
//Apply borders to the Sales data and headers.
oResizeRange = oWS.get_Range("E1", "E6").get_Resize( Missing.Value, iNumQtrs);
oResizeRange.Borders.Weight = Excel.XlBorderWeight.xlThin;
//Add a Totals formula for the sales data and apply a border.
oResizeRange = oWS.get_Range("E8", "E8").get_Resize( Missing.Value, iNumQtrs);
oResizeRange.Formula = "=SUM(E2:E6)";
oResizeRange.Borders.get_Item( Excel.XlBordersIndex.xlEdgeBottom ).LineStyle
= Excel.XlLineStyle.xlDouble;
oResizeRange.Borders.get_Item( Excel.XlBordersIndex.xlEdgeBottom ).Weight
= Excel.XlBorderWeight.xlThick;
//Add a Chart for the selected data.
oWB = (Excel._Workbook)oWS.Parent;
oChart = (Excel._Chart)oWB.Charts.Add( Missing.Value, Missing.Value,
Missing.Value, Missing.Value );
//Use the ChartWizard to create a new chart from the selected data.
oResizeRange = oWS.get_Range("E2:E6", Missing.Value ).get_Resize(
Missing.Value, iNumQtrs);
oChart.ChartWizard( oResizeRange, Excel.XlChartType.xl3DColumn, Missing.Value,
Excel.XlRowCol.xlColumns, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value );
oSeries = (Excel.Series)oChart.SeriesCollection(1);
oSeries.XValues = oWS.get_Range("A2", "A6");
for( int iRet = 1; iRet <= iNumQtrs; iRet++)
{
oSeries = (Excel.Series)oChart.SeriesCollection(iRet);
String seriesName;
seriesName = "=\"Q";
seriesName = String.Concat( seriesName, iRet );
seriesName = String.Concat( seriesName, "\"" );
oSeries.Name = seriesName;
}
oChart.Location( Excel.XlChartLocation.xlLocationAsObject, oWS.Name );
//Move the chart so as not to cover your data.
oResizeRange = (Excel.Range)oWS.Rows.get_Item(10, Missing.Value );
oWS.Shapes.Item("Chart 1").Top = (float)(double)oResizeRange.Top;
oResizeRange = (Excel.Range)oWS.Columns.get_Item(2, Missing.Value );
oWS.Shapes.Item("Chart 1").Left = (float)(double)oResizeRange.Left;
}
Based on your edit try the following:
result.ForEach(w => {
Excel.Range objRange = w.get_Range("C3", Missing.Value);
string colLengthStr = objRange.Value2;
}