carloscds posted on December 13, 2009 11:47

Hoje em dia é muito comum recebermos dados em planilhas do Excel e ter que importar ou analisar estes dados em nossas aplicações.

Com a ajuda do .Net Framework esta tarefa fica muito fácil e vou demonstrar como você pode abrir um arquivo do Excel e executar um comando Select em uma planilha simplesmente usando Ado.Net.

Para começar, vamos mostrar como está a nossa planilha no Excel e quais as informações importantes para o nosso programa em .Net.

Nossa planilha tem estes dados:

image

Vejam que a planilha tem os títulos das colunas na primeira linha. Estes serão os nomes dos campos para o nosso comando Select, e também o nome da planilha, que é Sheet1, será o nome da nossa tabela.

Agora vamos criar um projeto do tipo Console no Visual Studio:

image

Obs: no meu exemplo estou usando o Visual Studio 2010, mas vocês podem usar o Visual Studio 2008 com .Net Framework 2.0 sem problemas.

Criada nossa solução, vamos agora escrever o código. Para acessar os dados na planilha, vamos usar o Ado.Net e DataSet, para ser mais fácil de entender, e sendo assim precisamos incluir os namespaces apropriados:


using
System.Data;
using System.Data.OleDb;

Após isto, precisamos criar a conexão com a planilha, usando OleDB:


OleDbConnection
conexao = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\temp\planilha.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES';");


Nesta conexão, usamos o provider Microsoft.ACE.OLEDB e indicamos o noem da planilha, bem como a versão do Excel.

Criaremos agora um Adapter para executar o comando Select, e também um DataSet para armazenar os dados da consulta:


OleDbDataAdapter
adapter = new OleDbDataAdapter("select * from [Sheet1$]", conexao);
DataSet ds = new DataSet();


Observem que o nome da planilha tem um símbolo ‘$’ ao final e está entre colchetes ‘[]’.

Agora vamos abrir a conexão, preencher o DataSet e exibir os dados da planilha:


try
{
   conexao.Open();
   adapter.Fill(ds);

   foreach (DataRow linha in ds.Tables[0].Rows)
   {
     Console.WriteLine("Nome: {0} - Cargo: {1} - Salario: {2}", linha["nome"].ToString(),
                        linha["cargo"].ToString(), linha["salario"].ToString());
   }
}
catch (Exception ex)
{
   Console.WriteLine("Erro ao acessar os dados: " + ex.Message);
}
finally
{
   conexao.Close();
}


Entendendo o código, abrimos a conexão, preenchemos o DataSet com o método Fill() do Adapter e depois executamos um ForEach para exibir os dados. Fazemos também o tratamento de exceção caso ocorra algum erro.

Vocês devem ter percebido que é um código bastante simples, mas de grande ajuda.

[]s,

Carlos.


Posted in: Visual Studio , C# , Visual Studio  Tags:

Comments


January 11. 2010 08:57
acai berry berries diet scams
I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

http://www.azcentral.com/members/Blog/Acaiberrydietdetoxhttp://www.azcentral.com/members/Blog/Acaiberrydietdetox


January 11. 2010 15:11
Astral Projection
Well, this is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a marvellous job!

http://astralprojectnow.com/t/go.php?c=seo4bloghttp://astralprojectnow.com/t/go.php?c=seo4blog


January 19. 2010 20:17
colloidal silver uses
I must say that overall I am really impressed with this blog.It is easy to see that you are passionate about your writing. If only I had your writing ability I look forward to more updates and will be returning.

http://liquidcolloidalsilver.net/http://liquidcolloidalsilver.net/


January 22. 2010 13:51
GED Online
Hello,I love reading through your blog, I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.

http://hubpages.com/hub/How-To-Get-Your-GEDhttp://hubpages.com/hub/How-To-Get-Your-GED


January 27. 2010 02:14
IR35 Rules
Excellent read, I just passed this onto a colleague who was doing a little research on that. And he actually bought me lunch because I found it for him smile So let me rephrase that: Thanks for lunch!

http://www.freelancesupermarket.com/resources/ir35-rules---a-guide-for-freelancers-and-contractors.aspxhttp://www.freelancesupermarket.com/resources/ir35-rules---a-guide-for-freelancers-and-contractors.aspx


January 29. 2010 05:17
leren hoekbank
I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.

http://www.dehoekbankshop.nl/category.php?id_category=6http://www.dehoekbankshop.nl/category.php?id_category=6


January 30. 2010 18:26
data backup
Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

http://www.backupcity.dk/http://www.backupcity.dk/


February 2. 2010 20:31
eagle idaho home search
Dude.. I am not much into reading, but somehow I got to read lots of articles on your blog. Its amazing how interesting it is for me to visit you very often.

http://www.vizionsrealestate.com/idaho/eagle/http://www.vizionsrealestate.com/idaho/eagle/


February 5. 2010 21:02
free press release
Keep 'em coming... you all do such a great job at such Concepts... can't tell you how much I, for one appreciate all you do!

http://www.free-press-release.com/http://www.free-press-release.com/


February 6. 2010 20:16
cheap fashion jewelry
I personally have embraced the new technologies and the CMS platforms, I think the new tools only make the web designs better. I am glad that new technologies are coming out in web design that make things easier, improved, and better looking for design.

http://jewelryfashionz.com/http://jewelryfashionz.com/


February 9. 2010 07:46
quality
While this subject can be very touchy for most people, my opinion is that there has to be a middle or common ground that we all can find. I do appreciate that youve added relevant and intelligent commentary here though. Thank you!

http://germancontent.wordpress.com/http://germancontent.wordpress.com/


February 12. 2010 13:59
Edmonds Garage Door Repair
Howdy, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam comments? If so how do you prevent it, any plugin or anything you can advise? I get so much lately it's driving me mad so any assistance is very much appreciated.

http://www.4garage-doors.com/edmonds-wa-garage-door-repair.aspxhttp://www.4garage-doors.com/edmonds-wa-garage-door-repair.aspx


February 13. 2010 09:27
budweiser neon sign
I must say that overall I am really impressed with this blog.It is easy to see that you are passionate about your writing. If only I had your writing ability I look forward to more updates and will be returning.

http://hubpages.com/hub/Budweiser-Neon-Sign-Perfect-for-the-Bar-Restaurant-or-Basementhttp://hubpages.com/hub/Budweiser-Neon-Sign-Perfect-for-the-Bar-Restaurant-or-Basement


February 17. 2010 13:31
acnezine
I admit, I have not been on this webpage in a long time... however it was another joy to see It is such an important topic and ignored by so many, even professionals. I thank you to help making people more aware of possible issues.
Great stuff as usual...

http://www.acnetorium.com/acnezine/http://www.acnetorium.com/acnezine/


February 25. 2010 01:59
shop a lu
I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

http://www.shopalu.com/http://www.shopalu.com/


March 2. 2010 16:14
cloud b sleep sheep
You got a really useful blog I have been here reading for about an hour. I am a newbie and your success is very much an inspiration for me.

http://hubpages.com/hub/Cloud-B-Sleep-Sheephttp://hubpages.com/hub/Cloud-B-Sleep-Sheep


March 5. 2010 13:15
free coupons and samples
Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!

http://www.couponsandsamplesfree.com/http://www.couponsandsamplesfree.com/


March 8. 2010 04:45
Umbrella Companies
I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

http://www.umbrellacompanies.org/http://www.umbrellacompanies.org/


March 8. 2010 04:45
Umbrella Companies
I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

http://www.umbrellacompanies.org/http://www.umbrellacompanies.org/


March 9. 2010 05:50
WoW Mobile
Do you know which cell phone companies allow tethering?

http://wowmobiles.org/http://wowmobiles.org/

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Sobre mim

Tenho mais de 20 anos de experiência no desenvolvimento de softwares. Sou certificado Microsoft MCP, Microsoft MVP C#. Sou palestrante em diversos eventos Microsoft, tenho diversos artigos publicados em revistas e participo dos fóruns do MSDN.
Vocês podem encontrar mais sobre mim em:

Busca no Blog

Comentários Recentes

Banners

Theme Grabber
Aviso
As opiniões colocadas neste blog são minhas e pessoais e não expressam necessariamente as opiniões de meus empregadores, pareceiros e amigos. Da mesma forma, os comentários feitos por leitores do blog não expressam a minha opinião.

© Copyright 2010 Carlos dos Santos