Chart Validation - c#

I'm gonna make a project to convert data and chart to powerpoint file to excel file.
but I found some problem here,,
I have make a project to convert chart, with this script
public static void GetChart(string strFilePath, string strDestPath)
{
xl.Application xlApp;
xl.Workbook xlWorkBook;
xl.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new xl.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(strFilePath, 0, true, 5,
"", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
"\t", false, false, 0, true, 1, 0);
xlWorkSheet =
(xl.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xl.ChartObjects xlCharts =
(xl.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
xl.ChartObject myChart = (xl.ChartObject)xlCharts.Item(1);
xl.Chart chartPage = myChart.Chart;
and then I convert it into an image with this script
GetChart(#"" + textBox1.Text + "", #"d:\" + textBox2.Text + ".jpeg");
label5.Text = #"D:\" + textBox2.Text + ".jpeg";
pictureBox1.Image = new Bitmap(#"" + label5.Text +
"");
but I think not all of excel file contains a chart, so I try to search a validation about how to detect a chart in every excel file.
How should I do ?

Try checking the number of items in the charts collection, ie xlCharts.Count

Related

How to read key value pairs from excel sheet using c#?

I'm new to C#. I have used the code below to read data from Excel, but I need help modifying it to read key-value pairs.
public String getData(int row, int col, String var)
{
Excel.Application excelApp = new Excel.Application();
if (excelApp != null)
{
List<string> prop = new List<string>(var.Split(new string[] {"."}, StringSplitOptions.None));
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(#"D:\\test.xlsx", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets[prop[0]];
excelWorksheet.Select(Type.Missing);
Excel.Range range = (excelWorksheet.Cells[row, col] as Excel.Range);
string cellValue = range.Value.ToString();
excelWorkbook.Close();
excelApp.Quit();
return cellValue;
}
return null;
}
Here is an example; it assumes you have a using clause..
using Excel = Microsoft.Office.Interop.Excel;
..and prepared access to a worksheet:
Excel.Application xl = new Excel.Application();
xl.Workbooks.Open(filename);
Excel.Worksheet ws = xl.Workbooks[1].Worksheets[1]; // pick your sheet!
int keyColum = 3;
Now you can grab a Range of Cells:
Excel.Range keyRange= ws.Range["C3:C53"];
..or the whole column:
Excel.Range keyRange= ws.Range["C:C"];
And search all occurences of a search string:
Excel.Range keysFound = keyRange.Find(textBox1.Text);
Then you can access the range of found cells like this:
string msg1 = keysFound.Count + " records found.";
string msg2 = "1st in row " + keysFound.Row;
string msg3 = "value from next column is "
+ ws.Cells[keysFound.Row + 1, keyColum + 1].value;
notes:
indexing start with 0 in c# but not in excel (hence [keysFound.Row + 1, )
my value column is one column right of the keys. Best use named indices!
if nothing is found keysFound will be null! (do add a check!)
since you want to match a whole key, you will want to do an exact search:
Excel.Range keysFound = keyRange.Find(textBox1.Text, LookAt: Excel.XlLookAt.xlWhole);
I still think grabbing all data and stuffing them into a Dictionary will be the cleanest and fastest solution, unless, that is you only need to do one lookup..

get_Address() not in correct format

I am performing search within excel workbook using small c# application.
now, when match found I am trying to get the full row details and the bounded into datagridview as shown below, but my problem is that
get_Address(true, true, Excel.XlReferenceStyle.xlR1C1, missing, missing)
is not show in correct format within the select statement
SELECT * FROM [Sheet1$B14:I24] //correct format
SELECT * FROM [sheet$B952]
so I am getting error message says
The Microsoft Access database engine could not find the object
'sheet$B952'. Make sure the object exists and that you spell its name
and the path name correctly. If 'sheet$B952' is not a local object,
check your network connection or contact the server administrator.
I tried to use get_AddressLocal or the xlA1 style but that is wont help me
to get the correct format
please if anyone can help or provide me with better solution or scenario
Thank alot
private void B_General_Search_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook oWB;
Microsoft.Office.Interop.Excel.Range currentFind = null;
Microsoft.Office.Interop.Excel.Range firstFind = null;
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DefaultDirectory + #"\new29.xlsx" + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\";";
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
if (string.IsNullOrEmpty(TB_Search_Text.Text))
{
MessageBox.Show("enter text for search");
return;
}
object missing = System.Reflection.Missing.Value;
oWB = oXL.Workbooks.Open(DefaultDirectory + #"\new29.xlsx", //---Filename OR FilePath
0, //---object UpdateLinks
true, //---object ReadOnly
missing, //5//---object Format
"", //---object Password
"", //---object WriteResPassword
false, //---object ReadOnlyRecommend
Excel.XlPlatform.xlWindows, //---object Origin
"", //---object Delimiter
true, //---object Editable
false, //---object Notify
0, //---object Converter
true, //---object AddToMru
false, //---object Local
false); //---object CorruptLoad;
//loop to search witin all excel sheets (workbook)
foreach (Excel.Worksheet SheetID in oWB.Worksheets)
{
Excel.Range oRng = oXL.get_Range("A1", "XFD1048576");
currentFind = oRng.Find(TB_Search_Text.Text,
missing,
Excel.XlFindLookIn.xlValues,
Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByRows,
Excel.XlSearchDirection.xlNext,
false,
missing,
missing);
while (currentFind != null)
{
//Keep track of the first range you find.
if (firstFind == null)
{
firstFind = currentFind;
}
else if (currentFind.get_Address(true, true, Excel.XlReferenceStyle.xlR1C1, missing, missing) == firstFind.get_Address(true, true, Excel.XlReferenceStyle.xlR1C1, missing, missing))
{
break;
}
//currentFind.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
//currentFind.Font.Bold = true;
currentFind = oRng.FindNext(currentFind);
//SELECT * FROM [Sheet1$B14:I24] correct format
//SELECT * FROM [sheet$B952] XXXXX
string cmdtxt = #"select * from [" + SheetID.Name + "$" + currentFind.get_Address(true, true, Excel.XlReferenceStyle.xlR1C1, missing, missing) + "]";
MessageBox.Show(cmdtxt);
using (OleDbConnection conn = new OleDbConnection(ConnStr))
{
OleDbDataAdapter DA = new OleDbDataAdapter(cmdtxt, conn);
DA.Fill(dt);
DGV_Data.DataSource = dt;
conn.Close();
}
}
}
oWB.Close(false, missing, missing);
//oSheet = null;
oWB = null;
oXL.Quit();
}

Merging different worksheets of workbook

The whole app works fine, when merging single tabbed workbooks. But then I added functionality to also merge all worksheets in a book, before merging the book with another.
It merges them (tested on a single multitabbed wbook), but at some point starts to mess it up.
For example
outcome:
sheet1
-empty lines- sheet2
-empty lines- sheet3+ half of sheet4
-empty lines- sheet2 again not all, with some values missing
etc...
Im not sure if is the code that needs something extra, or problems in certain worksheets.
Heres the crucial parts:
for (int i = 0; i < pathList.Count; i++)
{
List<string> Sheet = GetSheetName(path);
filename = GetFileName(path);
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + path + "';Extended Properties='Excel 8.0;IMEX=1;'");
foreach (string SheetName in Sheet)
{
//OLEDB SECTION ***********************************************
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + SheetName + "$]", MyConnection);
MyCommand.TableMappings.Add(pathList.Count.ToString(), filename);
MyCommand.Fill(table);
lstTable.Add(table);
MyConnection.Close();
MyCommand.Dispose();
//*************************************************************
}
}
and the getSheetNames
List<string> GetSheetName(string path)
{
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
List<string> names = new List<string>();
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
foreach (Microsoft.Office.Interop.Excel.Worksheet i in xlWorkBook.Worksheets)
if (i.UsedRange.Count > 0)
names.Add(i.Name);
return names ;
}

Open, Modify, SaveAs an Excel Workbook in the background (Winforms, C#)

in my app, I've saved a copy of a blank excel file form as a resources, I need to load this file, modify its both worksheets, save it in a new location with a new name.
user should not see that process.
I'm using C# 2010 with a SQL server, from which I'm gonna load my data and put it in the excel form.
Thank You For Your Time.
Use the Microsoft Interop Assemblies that can be found in .NET or COM (Microsoft.Office.Interop.Excel)
Then load all the required cells into a List and modify the data.
Something like this (code below):
string path = #"C:\temp\test.xls";
ApplicationClass excelApllication = null;
Workbook excelWorkBook = null;
Worksheet excelWorkSheet = null;
excelApllication = new ApplicationClass();
System.Threading.Thread.Sleep(2000);
excelWorkBook = excelApllication.Workbooks.Add();
excelWorkSheet = (Worksheet)excelWorkBook.Worksheets.get_Item(1);
// Attention: 1 indexed cells, [Row, Col]
excelWorkSheet.Cells[1, 1] = "Column A, Row 1";
excelWorkSheet.Cells[2, 5] = "Column E, Row 2";
excelWorkSheet.Cells[3, 3] = "Column C, Row 3";
excelWorkBook.SaveAs(path, XlFileFormat.xlWorkbookNormal);
excelWorkBook.Close();
excelApllication.Quit();
Marshal.FinalReleaseComObject(excelWorkSheet);
Marshal.FinalReleaseComObject(excelWorkBook);
Marshal.FinalReleaseComObject(excelApllication);
excelApllication = null;
excelWorkSheet = null;
//opens the created and saved Excel file
Process.Start(path);
That should happen inside a Thread, because you don't want a user to notice that task.
http://msdn.microsoft.com/en-us/library/aa645740%28v=vs.71%29.aspx
(Threading Tutorial)
I would try to avoid automating Excel if at all possible and use the OpenXML SDK (or a library wrapping the OpenXML SDK) for this task.
Here is an article that could help you get started.
I think you wanted to do this... at least worked for me. :)
private void btnExcel_Click(object sender, EventArgs e)
{
string newDirectoryPath = ValidateDirectory();
string newFilePath = Path.Combine(newDirectoryPath, "new.xls");
//brand new temporary file
string tempPath = System.IO.Path.GetTempFileName();
//to manage de temp file life
FileInfo tempFile = new FileInfo(tempPath);
//copy the structure and data of the template .xls
System.IO.File.WriteAllBytes(tempPath,Properties.Resources.SomeResource);
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(tempPath, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//WorkTheExcelFile();
tempFile.Delete();
xlWorkBook.SaveAs(newFilePath);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
Process.Start(newFilePath + ".xlsx");
}

How to append a data to existing excel file using c#

I want to append a data to a existing excel file using c#.I Tried it using below codes,but it is giving wrong column value after opening of the excel file(if my excel file contains 4 columns,but here it is returning column count as 1 only).
xlApp = new Excel.Application();
xlApp.Visible = true;
xlWorkBook = xlApp.Workbooks.Open(fileName, 0, false, 5, "", "", false,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, 1, 0); //#"H:\TestFile.xlsx"
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets.get_Item(sheetNum);
rng = xlWorkSheet.UsedRange;
int colCount = rng.Columns.Count;
int rowCount = rng.Rows.Count;
rng = (Excel.Range)xlWorkSheet.Cells[rowCount, colCount];
Excel.Range newColumn = rng.EntireColumn;
xlWorkSheet.Cells[1, colCount + 3] = "Udupi";
xlWorkBook.Save();
xlWorkBook.Close(misValue, misValue, misValue);
xlApp.Quit();
How can i append a data to excel file?Is there any other methods are available to achieve this one!
Have you tried Epplus library for creating and editing Excel spreadsheets and workbooks in C#? I have worked on it before some weeks ago. It is super. I recommend to use it.

Categories

Resources