C# 操作Excel [不确定sheet name]
上一篇 / 下一篇 2008-05-09 15:45:17 / 个人分类:做着
C#操作Excel我掌握两种方法ITPUB个人空间|Hep$XM
1.Microsoft.Jet.OLEDB.4.0ITPUB个人空间+q*A
w|m
操作简单,但不知道某种原因,部分Cell不能正确读取到.
2.Excel.ApplicationClassITPUB个人空间*t:?M"u`(c
h(rg
操作相对复杂,功能多一些.
遇到问题:由于方法1不能正确读取Excel数据,所以选择方法2.但是sheet name不知,方法二不能操作Excel,不能确定sheetName.ITPUB个人空间N/] T/a;QS8Y
解决:使用方法1获取到Excel中所有SheetName,在方法2中使用这个结果.
Source:
using System;ITPUB个人空间/v3[:k
D4n)e4v3K(Bw
using System.Data;
$uom
t-Rt|T0using System.Data.OleDb;ITPUB个人空间ht5J!r;j!k
using System.IO;ITPUB个人空间7{P[jq](e
using System.Collections;
'~8Q
VAHB%`&@c&w|0using Excel;
namespace ImportIDPSCDITPUB个人空间[:U;J*o1dG6x
{
v!`T%l.Au+h:C^0 /// <summary>ITPUB个人空间)ILq
Y.`vw
/// Input of IDP and SCD Spending per day .ITPUB个人空间}c7z @W U\y'@
/// </summary>
+b"?-EH-p'xx
z&M?0 class ImportIDPSCD
)AtqTo EMii\$@0 {
Y9a:?TXC0 // IDP and SCD Spendin File Path
4a f h{UC.xN0 private static string filePath = string.Empty;
1l'cB8F$[3C&W{0 // DB Connect StringITPUB个人空间"|_yjp;_Y:Z
private static string strDBManager = string.Empty;
/// <summary>ITPUB个人空间O|:`/Bvmx4?
/// Input of IDP and SCD Spending per day .
/{Du,}/p^)I8M0 /// </summary>ITPUB个人空间#bw2Sy)v,n5l;f(b
[STAThread]ITPUB个人空间#V9J.Zg b5M4o8gY]
static void Main(string[] args)
2D+h+x;wM:|Aq3~0 {
cRI5aC~0he0 // Get File PathITPUB个人空间a{*u{@,i[
filePath = System.Configuration.ConfigurationSettings.AppSettings["XXX"];
f&PTx5{8I0 // Get DB ConnecctITPUB个人空间*?9]gHV0Vt
strDBManager = System.Configuration.ConfigurationSettings.AppSettings["YYY"];ITPUB个人空间"u0]TG2@{,f
// Get FileITPUB个人空间TUzM`*ZN X
string[] fileEntries = Directory.GetFiles(filePath);ITPUB个人空间7\#c;p_I.F&`:[+S
foreach(string fileName in fileEntries)ITPUB个人空间;g8X'[_3gQ6EFx
{ITPUB个人空间p0D$I"L
f!Wm J*C\
// Get Excel File
"hUQ(Q+_+dg,Z0 GetFileFull(fileName);
!])R8zfoH z%Re0 }
2c PX!bc0 }
/// <summary>
(o fG2\2|6vaVl*w5K/y0 /// Get Excel Data.
7|0Z9X%rp L0 /// </summary>
9mpz.\/{s.aaG0 /// <param name="fileName">file Name</param>
tp;k2I^3Sl%Q8Z0 /// <returns>int</returns>
d
Jw||IbaBF0 private static int GetFile(string fileName)ITPUB个人空间!Kmzlh.?9j
{
0c0w3g L6}a"@
w-j0 // Read Excel File ConnectITPUB个人空间y3MH;ms0] K$H
string excelConnect = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + fileName + ";Extended Properties=Excel 8.0";
'JVf GE/\b0 string excelCom = string.Empty;
!J)aX+s5E)`B8]&s0 OleDbConnection excelConn = new OleDbConnection(excelConnect);ITPUB个人空间,X.G8l\
Z#W9Be
n]iF/Oo3t0 try
Qy5?@[G0 {
O:q.b,w!WIhF0 // Open Excel
5]fK*{^m [0 excelConn.Open();
)?#{t7_B1x0 System.Data.DataTable excelDT = null;
z!tHc
K0 excelDT = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
_dxs5|%l+S0 int i = 0;ITPUB个人空间xVc}B-O:[2d
// Add the sheet name to the string array.ITPUB个人空间 r*AHa0j"j%mowo
foreach(DataRow row in excelDT.Rows)ITPUB个人空间]e*G0_|1F.S
{
hF*TN3X:I$^$Uu0 DataSet excelDataSet = new DataSet();ITPUB个人空间c g m4BC)k
// Get sheet Name.ITPUB个人空间$K R5eAdwP
string sheetName = row["TABLE_NAME"].ToString();ITPUB个人空间 qd&i3K^
i++;ITPUB个人空间J3y(y8LS
excelCom = " SELECT * FROM [" + sheetName + "]";
r6G8~G7L(X5tP0 OleDbDataAdapter excelAdap = new OleDbDataAdapter(excelCom , excelConn); ITPUB个人空间z1l+GVVPH7pe3UUo
// Get Excel DataITPUB个人空间e\/F[
Nd:Qx
excelAdap.Fill(excelDataSet, "sheet1");
"a ];}K*B6H~w[5A0 // Import Excel DataITPUB个人空间M@r'oy$J4op8@}
ImportFile(excelDataSet);
g,N5a~ZN
thC:g0 }ITPUB个人空间5X+zD3vE1m)XFy
}ITPUB个人空间`+?w8G}
S3t
catch(Exception ex)ITPUB个人空间\h8A}(x"E{Ju
{
{
RM.| s0 Console.WriteLine(ex.Message);
L"B$g#@j&R5]]Y0 return -1; ITPUB个人空间 ?:m[1rT
}
1J8o;KRT~m:y$c,a0 finallyITPUB个人空间:d#b&]V c*|O
{
,P"bsTj`6nQ.|0 if(excelConn != null)ITPUB个人空间]AAP|T`
_
{ITPUB个人空间4lr3Dp8X
rJ&EKd(n
excelConn.Close();
5dh%C.?.xCRO!G0 excelConn = null;
pq*~2q~GOc/Q0 }ITPUB个人空间G#d}~2my
}
return 0;ITPUB个人空间.R/@!W F|;_h2WE)y
}
/// <summary>
qe:Lg/Z&\0 /// Get ExcelFileITPUB个人空间;H3J;G1D/[f5a
/// </summary>
}t{rRx0 /// <param name="fileName">File Name</param>ITPUB个人空间F
r]8f W&L\p
/// <returns>int</returns>ITPUB个人空间&Y'A#QC;l%bq:G:AY
private static int GetFileFull(string fileName)ITPUB个人空间A'z+Brqt]grS
{
!z'X'TAm+a6[0 // Excel Data
X L&q6Kg#Dy0 DataSet allDS = new DataSet();ITPUB个人空间-c
G8la,^.ph
// Sheets Name
8k$S!}bj0e0 String[] excelSheetsName = null;ITPUB个人空间$JoWA4[2l
// All Cell Value of a Sheet
/k^1|&y/g`c2X0 ArrayList allCellValue = new ArrayList();
// Read Excel File Connect
"xT2g-Ccb&h
eMS2q0 string excelConnect = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + fileName + ";Extended Properties=Excel 8.0";ITPUB个人空间_iJ#UH6bg
string excelCom = string.Empty;ITPUB个人空间2{7NHK Pk+AY
OleDbConnection excelConn = new OleDbConnection(excelConnect);
// Creates a new Excel ApplicationITPUB个人空间1Iv0GW0g!A
Excel.Application excelApp = new Excel.ApplicationClass();ITPUB个人空间1dwxTAW9^O
// Makes Excel visible to the user.ITPUB个人空间*|9D:s|T|\a
excelApp.Visible = false;
?.z;\kWI"{0
!B&C1lQOr0 tryITPUB个人空间
Z W If
Dx^5j
{
ad:ommt wo0 // Open Excel
R&h#v5@s |&C6h3]0 excelConn.Open();
1e6~9X_'Iy
q0 System.Data.DataTable excelDT = null;
*_D$uV@z
b0 excelDT = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);ITPUB个人空间%cm3n:p,] `M4L
excelSheetsName = new String[excelDT.Rows.Count];ITPUB个人空间&SJ9R+UIf&i x;V%aQ;N
int i = 0;ITPUB个人空间i2K"d%m
J(b5F3k
// Add the sheet name to the string array.
8o|`EB[Ki0 foreach(DataRow row in excelDT.Rows)
{L3V'K_cP]!G0 {
cF)Wi1z/\6{Yu0 // Get sheet Name.ITPUB个人空间 b Wcj&@
excelSheetsName[i] = row["TABLE_NAME"].ToString();ITPUB个人空间1b ~h0p+^
]q3s
i++;
:?8s nDc9t0 }
// Get Excel Data Command
~eia_(~;{mj0 excelCom = " SELECT * FROM [" + excelSheetsName[0] + "]";
X;\@` G.b%S(\D9]0 OleDbDataAdapter excelAdap = new OleDbDataAdapter(excelCom , excelConn); ITPUB个人空间N EF
C2Kgi6}0hs
// Get Excel DataITPUB个人空间A]3f;{-sA#r X
excelAdap.Fill(allDS, "AllDS");
// Close Open Object
os``
`bH6^/k0 if(excelConn != null)ITPUB个人空间b;zPb;~r8y
{
t.w-R#h+X G0{
d
E0 excelConn.Close();
2t2~"^f4|f\0Og(l,l"l0 excelConn = null;
2eX1p aPM,d0 }ITPUB个人空间c&`4m7Ah)j!r5D-{
#region Execute Excel
// Opens existing workbookITPUB个人空间[
`\ {~PU(moM
string workbookPath = fileName;ITPUB个人空间o1hN-UN
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0,
.A8OVjH0 false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true,ITPUB个人空间FJ w(]vj$V
false, 0, true, false, false);
xGg3Z!w)Y4g
OU]0
I?wsP
p#DwJ_]0 // Gets the Worksheets collectionITPUB个人空间 {3^
r1V&A4z
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
// Gets Sheet Name for WorksheetsITPUB个人空间u9k$Wf4Vl0J
string currentSheet = excelSheetsName[0].Replace("$", "").Replace("'", "");
it+ut4I I-fW2F(A0 Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
// For each the sheet Data
AXNjVDgt0 for(int index = 4; index < allDS.Tables[0].Rows.Count - 1; index++)ITPUB个人空间7cGN(B)\Du
a
{ITPUB个人空间jzBp-dmYJC
t]*s
if(allDS.Tables[0].Rows[index][0] != null && !allDS.Tables[0].Rows[index][0].ToString().Equals(""))ITPUB个人空间s1p_rUl
{
h*OS8X&u|E
R;@0 // Gets cellITPUB个人空间6Ot%SgGw#W#O x]
int lineNumber = index + 2;ITPUB个人空间?h
r0|R3V9D)KJ
Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range("A" + lineNumber, "G" + lineNumber);
// Keep Data
,kGkzd2HU0 object [,] cellValue = (object[,])excelCell.Value2;
&K