UC_EmbedExcelIntoWinFormNoDLL.cs 264 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Drawing;
  5. using System.Data;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.Reflection;
  9. using System.Runtime.InteropServices; //调用API
  10. namespace SuperTools
  11. {
  12. #region (动态类)嵌入excel.exe应用程序到c#(V2.0)的WinForm里面
  13. /// <summary>
  14. /// 嵌入excel.exe应用程序到c#(V2.0)的WinForm里面
  15. /// 作者:yuanshou.如有问题,请联系:yuanshou@21cn.com
  16. /// </summary>
  17. public partial class UC_EmbedExcelIntoWinFormNoDLL : UserControl
  18. {
  19. #region 控件本身生成
  20. /// <summary>
  21. /// 必需的设计器变量。
  22. /// </summary>
  23. private System.ComponentModel.IContainer components = null;
  24. /// <summary>
  25. /// 清理所有正在使用的资源。
  26. /// </summary>
  27. /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
  28. protected override void Dispose(bool disposing)
  29. {
  30. AppExcel_Exit();   //调用退出
  31. //*******************************
  32. //C:\Documents and Settings\Administrator\Application Data\Microsoft\Excel\Excel11.xlb
  33. string LoginName = System.Environment.UserName; //计算机名字
  34. string strExcelStyleFileName = "C:\\Documents and Settings\\" + LoginName + "\\Application Data\\Microsoft\\Excel\\Excel11.xlb";
  35. if (System.IO.File.Exists(strExcelStyleFileName) == true)
  36. {
  37. System.IO.File.Delete(strExcelStyleFileName);
  38. }
  39. //********************
  40. if (disposing && (components != null))
  41. {
  42. components.Dispose();
  43. }
  44. base.Dispose(disposing);
  45. }
  46. #region 组件设计器生成的代码
  47. /// <summary>
  48. /// 设计器支持所需的方法 - 不要
  49. /// 使用代码编辑器修改此方法的内容。
  50. /// </summary>
  51. private void InitializeComponent()
  52. {
  53. this.SuspendLayout();
  54. //
  55. // UC_EmbedExcelIntoWinFormNoDLL
  56. //
  57. this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
  58. this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  59. this.Name = "UC_EmbedExcelIntoWinFormNoDLL";
  60. this.Size = new System.Drawing.Size(149, 132);
  61. this.Load += new System.EventHandler(this.UC_EmbedExcelIntoWinFormNoDLL_Load);
  62. this.SizeChanged += new System.EventHandler(this.UC_EmbedExcelIntoWinFormNoDLL_SizeChanged);
  63. this.ResumeLayout(false);
  64. }
  65. #endregion
  66. #endregion
  67. private IntPtr appSubWinHandle = IntPtr.Zero; //打开excel.exe窗体的句柄
  68. /// <summary>
  69. /// 构造函数
  70. /// </summary>
  71. public UC_EmbedExcelIntoWinFormNoDLL()
  72. {
  73. InitializeComponent();
  74. }
  75. private void UC_EmbedExcelIntoWinFormNoDLL_Load(object sender, EventArgs e)
  76. {
  77. }
  78. private void UC_EmbedExcelIntoWinFormNoDLL_SizeChanged(object sender, EventArgs e)
  79. {
  80. ReDraw();
  81. }
  82. #region 操作 excel
  83. private object m_objApp;
  84. private object m_objBooks;
  85. private object m_objBook;
  86. private object m_objSheets;
  87. private object m_objSheet;
  88. private DateTime LateBindingExcelStartTime;   //AppExcel 窗口启动时间
  89. private DateTime LateBindingExcelEndTime;   //AppExcel 窗口打开完毕后的时间
  90. /// <summary>
  91. /// 文件打开
  92. /// </summary>
  93. /// <param name="_ExcelFileName">打开的文件名字,默认打开激活的sheet1</param>
  94. /// <param name="_bEmbedExcelIntoWinForm">是否显示excel.exe应用程序的界面</param>
  95. /// <returns></returns>
  96. public void AppExcel_Open(string _ExcelFileName, bool _bEmbedExcelIntoWinForm)
  97. {
  98. AppExcel_Open(_ExcelFileName, 1, _bEmbedExcelIntoWinForm);
  99. }
  100. /// <summary>
  101. /// 文件打开
  102. /// </summary>
  103. /// <param name="_ExcelOpenFileName">打开的文件名字</param>
  104. /// <param name="_ActivatorSheet">选择激活的sheet序号,从1开始</param>
  105. /// <param name="_bEmbedExcelIntoWinForm">是否显示excel.exe应用程序的界面</param>
  106. /// <returns></returns>
  107. public bool AppExcel_Open(string _ExcelOpenFileName, int _ActivatorSheet, bool _bEmbedExcelIntoWinForm)
  108. {
  109. //if (_FileName == null) { return false; }
  110. if (m_objApp != null & m_objBook != null)
  111. { this.AppExcel_Exit(); }
  112. #region 实例化m_objApp,并打开m_objApp
  113. LateBindingExcelStartTime = System.DateTime.Now; //开始时间
  114. this.m_objApp = this.Get_App(); //获取Excel类型并建立其实例
  115. this.m_objBooks = this.Get_Books(this.m_objApp); //获取Workbook集
  116. this.m_objBook = this.Get_Book(this.m_objBooks, _ExcelOpenFileName);
  117. this.m_objSheets = this.Get_Sheets(this.m_objBook); //获取Sheet集
  118. this.m_objSheet = this.Get_Sheet(this.m_objSheets, _ActivatorSheet); //获取一个Sheet对象
  119. LateBindingExcelEndTime = System.DateTime.Now; //结束时间
  120. #endregion
  121. #region 获取句柄,并嵌入窗体
  122. if (_bEmbedExcelIntoWinForm)
  123. {
  124. this.SetApp_Visible(this.m_objApp, _bEmbedExcelIntoWinForm); //显示excel程序的界面,只有显示,才能获取句柄
  125. //this.SetApp_ExcelWindowState(2); // excel.exe程序可见后,最小化窗口
  126. this.appSubWinHandle = GetExcelProcessHandle(this.LateBindingExcelStartTime, this.LateBindingExcelEndTime);
  127. #region 嵌入窗体
  128. if (this.appSubWinHandle != IntPtr.Zero) //打开Excel窗口,并嵌入到WinForm中
  129. {
  130. this.EmbedIntoWindows();
  131. //this.SetApp_ExcelWindowState(1); //嵌入完后,显示 EXCEL.EXE的窗口正常显示
  132. this.SetApp_EmbedExcelStyle(); //设置嵌入excel的显示式样:隐藏系统菜单和命令快捷键
  133. return true;
  134. }
  135. else
  136. {
  137. MessageBox.Show("不能获取WinHandle,请关闭重新打开!");
  138. return false;
  139. }
  140. #endregion
  141. }
  142. else
  143. {
  144. return false;
  145. }
  146. #endregion
  147. }
  148. #region late Bing 的方法 设置说明
  149. //为了获取返回值,必须指定 BindingFlags.Instance 或 BindingFlags.Static。
  150. //可以使用下列 BindingFlags 调用标志表示要对成员采取的操作:
  151. //CreateInstance,表示调用构造函数。忽略 name。对其他调用标志无效。
  152. //InvokeMethod,表示调用方法,而不调用构造函数或类型初始值设定项。对 SetField 或 SetProperty 无效。
  153. //GetField,表示获取字段值。对 SetField 无效。
  154. //SetField,表示设置字段值。对 GetField 无效。
  155. //GetProperty,表示获取属性。对 SetProperty 无效。
  156. //SetProperty 表示设置属性。对 GetProperty 无效。
  157. //BindingFlags,枚举类型 如下:
  158. //BindingFlags.Instance : 对象实例
  159. //BindingFlags.Static : 静态成员
  160. //BindingFlags.Public : 指可在搜索中包含公共成员
  161. //BindingFlags.NonPublic : 指可在搜索中包含非公共成员(即私有成员和受保护的成员)
  162. //BindingFlags.FlattenHierarchy : 指可包含层次结构上的静态成员
  163. //BindingFlags.IgnoreCase : 表示忽略 name 的大小写
  164. //BindingFlags.DeclaredOnly : 仅搜索 Type 上声明的成员,而不搜索被简单继承的成员
  165. //BindingFlags.CreateInstance : 表示调用构造函数。忽略 name。对其他调用标志无效
  166. //举例:
  167. //对执行方法的,用 BindingFlags.InvokeMethod 如 sheet.Activate(),book.close();
  168. //对获取/设置属性的用GetProperty/SetProperty
  169. //BindingFlags SetPropFlags = BindingFlags.SetProperty | BindingFlags.Static | BindingFlags.Public |
  170. // BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase | BindingFlags.CreateInstance;
  171. #endregion
  172. #region 获取Excel类型并建立其实例
  173. /// <summary>
  174. /// 获取Excel类型并建立其实例
  175. /// </summary>
  176. /// <returns>Excel实例</returns>
  177. private object Get_App()
  178. {
  179. Type objExcelType = Type.GetTypeFromProgID("Excel.Application"); //Excel.Application //Word.Application //PowerPoint.Application //Outlook.Application
  180. if (objExcelType == null)
  181. {
  182. string strErr = "本计算机无Excel.Application";
  183. System.Windows.Forms.MessageBox.Show(strErr);
  184. return null;
  185. }
  186. //新建一个Excel.exe的进程
  187. object _objApp = Activator.CreateInstance(objExcelType);
  188. if (_objApp == null)
  189. {
  190. string strErr = "本计算机的Excel.Application无法正常使用!";
  191. System.Windows.Forms.MessageBox.Show(strErr);
  192. return null;
  193. }
  194. else
  195. {
  196. return _objApp;
  197. }
  198. }
  199. /// <summary>
  200. /// 获取Workbook集
  201. /// </summary>
  202. /// <param name="_objApp"></param>
  203. /// <returns></returns>
  204. private object Get_Books(object _objApp)
  205. {
  206. if (_objApp == null) { return null; }
  207. object m_objBooks = _objApp.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, _objApp, null);
  208. return m_objBooks;
  209. }
  210. /// <summary>
  211. /// 添加一个新的Workbook 或者 打开一个已经存在的Workbook
  212. /// </summary>
  213. /// <param name="_objBooks"></param>
  214. /// <param name="_strFileName">打开的文件名,如果为null,则新打开</param>
  215. /// <returns></returns>
  216. private object Get_Book(object _objBooks, string _strFileName)
  217. {
  218. if (_objBooks == null) { return null; }
  219. object m_objBook = new object();
  220. if (_strFileName == null)
  221. {
  222. //添加一个新的Workbook
  223. m_objBook = _objBooks.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, _objBooks, null);
  224. }
  225. else
  226. {
  227. //打开一个已经存在的Workbook
  228. #region 打开参数
  229. object o_Filename = _strFileName; // "123";
  230. object o_UpdateLinks = System.Reflection.Missing.Value;
  231. object o_ReadOnly = System.Reflection.Missing.Value;
  232. object o_Format = System.Reflection.Missing.Value;
  233. object o_Password = System.Reflection.Missing.Value;
  234. object o_WriteResPassword = System.Reflection.Missing.Value;
  235. object o_IgnoreReadOnlyRecommended = System.Reflection.Missing.Value;
  236. object o_Origin = System.Reflection.Missing.Value;
  237. object o_Delimiter = System.Reflection.Missing.Value;
  238. object o_Editable = System.Reflection.Missing.Value;
  239. object o_Notify = System.Reflection.Missing.Value;
  240. object o_Converter = System.Reflection.Missing.Value;
  241. object o_AddToMru = System.Reflection.Missing.Value;
  242. object o_Local = System.Reflection.Missing.Value;
  243. object o_CorruptLoad = System.Reflection.Missing.Value;
  244. object[] m_Parameters_objBooksOpen = new Object[15];
  245. m_Parameters_objBooksOpen[0] = o_Filename;
  246. m_Parameters_objBooksOpen[1] = o_UpdateLinks;
  247. m_Parameters_objBooksOpen[2] = o_ReadOnly;
  248. m_Parameters_objBooksOpen[3] = o_Format;
  249. m_Parameters_objBooksOpen[4] = o_Password;
  250. m_Parameters_objBooksOpen[5] = o_WriteResPassword;
  251. m_Parameters_objBooksOpen[6] = o_IgnoreReadOnlyRecommended;
  252. m_Parameters_objBooksOpen[7] = o_Origin;
  253. m_Parameters_objBooksOpen[8] = o_Delimiter;
  254. m_Parameters_objBooksOpen[9] = o_Editable;
  255. m_Parameters_objBooksOpen[10] = o_Notify;
  256. m_Parameters_objBooksOpen[11] = o_Converter;
  257. m_Parameters_objBooksOpen[12] = o_AddToMru;
  258. m_Parameters_objBooksOpen[13] = o_Local;
  259. m_Parameters_objBooksOpen[14] = o_CorruptLoad;
  260. #endregion
  261. m_objBook = _objBooks.GetType().InvokeMember("Open", BindingFlags.InvokeMethod, null, _objBooks, m_Parameters_objBooksOpen);
  262. }
  263. return m_objBook;
  264. }
  265. /// <summary>
  266. /// 获取Sheet集
  267. /// </summary>
  268. /// <param name="_objBook"></param>
  269. /// <returns></returns>
  270. private object Get_Sheets(object _objBook)
  271. {
  272. if (_objBook == null) { return null; }
  273. object m_objSheets = _objBook.GetType().InvokeMember("Worksheets", BindingFlags.GetProperty, null, _objBook, null);
  274. return m_objSheets;
  275. }
  276. /// <summary>
  277. /// 获取其中一个Sheet
  278. /// </summary>
  279. /// <param name="_objSheets"></param>
  280. /// <param name="_ActivatorSheet"></param>
  281. /// <returns></returns>
  282. private object Get_Sheet(object _objSheets, int _ActivatorSheet)
  283. {
  284. if (_objSheets == null) { return null; }
  285. //object[] m_Parameters_ActivatorSheet = new Object[1] { 1 }; //第一个sheet:sheet1
  286. object[] m_Parameters_ActivatorSheet = new Object[1] { _ActivatorSheet }; //第一个sheet:sheet1
  287. object m_objSheet = _objSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, _objSheets, m_Parameters_ActivatorSheet);
  288. this.SetSheet_ChangeActivateSheet(_ActivatorSheet);
  289. return m_objSheet;
  290. }
  291. #endregion
  292. //得到Excel进程ID的MainWindowHandle
  293. private static IntPtr GetExcelProcessHandle(DateTime beforeTime, DateTime afterTime)
  294. {
  295. IntPtr appProcessHandle = IntPtr.Zero;
  296. System.Diagnostics.Process[] myProcesses;
  297. DateTime startTime;
  298. myProcesses = System.Diagnostics.Process.GetProcessesByName("Excel");
  299. //得不到Excel进程ID,暂时只能判断进程启动时间
  300. foreach (System.Diagnostics.Process myProcess in myProcesses)
  301. {
  302. startTime = myProcess.StartTime;
  303. if (startTime >= beforeTime && startTime <= afterTime)
  304. {
  305. //myProcess.Kill();
  306. appProcessHandle = myProcess.MainWindowHandle;
  307. //private
  308. }
  309. }
  310. return appProcessHandle;
  311. }
  312. /// <summary>
  313. /// 嵌入窗体时,设置execel.exe应用程序嵌入窗体里面的显示式样
  314. /// </summary>
  315. /// <returns>是否成功</returns>
  316. private bool SetApp_EmbedExcelStyle()
  317. {
  318. this.SetApp_Exit_EditMode();
  319. try
  320. {
  321. this.SetApp_DisplayStatusBar(false); //状态栏
  322. this.SetApp_DisplayFormulaBar(false); //编辑栏
  323. this.SetApp_DisplayAlerts(false); //警告提醒
  324. //this.SetApp_DisplayFullScreen(false); //全屏
  325. //this.SetApp_DisableAskAQuestionDropdown(true); //用户提问帮助栏
  326. //this.SetApp_DisableCustomize(true); //用户自己定义菜单
  327. //this.SetCommandBar_Cell_Enabled(true); //可以右键弹出浮动菜单
  328. //this.SetApp_Display_DisplayHeadings(false); //禁止行号列标
  329. ////this.SetSheet_ChangeActivateSheet(1); //指定激活第一个sheet
  330. this.SetCell_ActiveCell("A1"); //指定激活第一个cell单元格
  331. ////this.SetSheet_DisplaySheet1_hiddenElseAllSheets(true); //隐藏除sheet1以外的其他的sheet
  332. //////直接指定设定
  333. //////this.App_SetAppWorksheetMenuBarEnabled(false); //excel的系统主菜单
  334. //////this.SetCommandBarName_Enabled("Worksheet Menu Bar", false);
  335. //////this.SetCommandBarName_Enabled("Standard", false);
  336. //////this.SetCommandBarName_Enabled("Cell", true);
  337. ////////"Standard" "Formatting" "Envelope" "Task Pane" "Tables" "Ink" "System" ""
  338. //////this.SetCommandBarName_Visible("Standard", false);
  339. //////this.SetCommandBarName_Visible("Formatting", false);
  340. //////this.SetCommandBarName_Visible("Envelope", false);
  341. //////this.SetCommandBarName_Visible("Task Pane", false);
  342. //////*********************************************
  343. //枚举所有的系统下拉菜单和命令快捷键全部隐藏和不可用
  344. this.SetCommandBars_IEnumeratorCommandBarsName();
  345. //this.SetApp_ExcelSystemMenu_xiala(false);
  346. return true;
  347. }
  348. catch (Exception ex)
  349. {
  350. MessageBox.Show("App设置显示式样有误!" + ex.Message);
  351. return false;
  352. }
  353. }
  354. /// <summary>
  355. /// 退出excel.exe的编辑模式 Edit Mode
  356. /// </summary>
  357. public void SetApp_Exit_EditMode()
  358. {
  359. if (m_objApp == null) { return; }
  360. if (m_objSheet == null) { return; }
  361. while (true)
  362. {
  363. try
  364. {
  365. this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
  366. bool bAppReady = (bool)m_objApp.GetType().InvokeMember("Ready", BindingFlags.GetProperty, null, m_objApp, null);
  367. this.Cursor = System.Windows.Forms.Cursors.Arrow;
  368. break; //如果excel.exe退出了编辑模式则退出循环
  369. }
  370. catch
  371. {
  372. myWin32API.SetForegroundWindow(this.appSubWinHandle);
  373. myWin32API.SetFocus(this.appSubWinHandle);
  374. //System.Threading.Thread.Sleep(100);
  375. System.Windows.Forms.SendKeys.SendWait("{ESC}"); //发送ESC键
  376. //System.Windows.Forms.SendKeys.Send("{ESC}"); //发送ESC键
  377. //System.Threading.Thread.Sleep(100);
  378. }
  379. }
  380. }
  381. public void SetApp_Exit_OKMode()
  382. {
  383. if (m_objApp == null) { return; }
  384. if (m_objSheet == null) { return; }
  385. while (true)
  386. {
  387. try
  388. {
  389. this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
  390. bool bAppReady = (bool)m_objApp.GetType().InvokeMember("Ready", BindingFlags.GetProperty, null, m_objApp, null);
  391. this.Cursor = System.Windows.Forms.Cursors.Arrow;
  392. break; //如果excel.exe退出了编辑模式则退出循环
  393. }
  394. catch
  395. {
  396. myWin32API.SetForegroundWindow(this.appSubWinHandle);
  397. myWin32API.SetFocus(this.appSubWinHandle);
  398. //System.Threading.Thread.Sleep(100);
  399. System.Windows.Forms.SendKeys.SendWait("{ENTER}"); //发送ESC键
  400. //System.Windows.Forms.SendKeys.Send("{ESC}"); //发送ESC键
  401. //System.Threading.Thread.Sleep(100);
  402. }
  403. }
  404. #region
  405. //IntPtr ip1 = myWin32API.GetActiveWindow();
  406. //IntPtr ip2 = myWin32API.GetForegroundWindow();
  407. //IntPtr ip3 = myWin32API.GetFocus();
  408. //myWin32API.SetFocus(this.appSubWinHandle);
  409. //System.Windows.Forms.SendKeys.Send("a"); //发送abcd
  410. //System.Windows.Forms.SendKeys.Send("{ESC}"); //发送ESC键
  411. //System.Windows.Forms.SendKeys.Send("{ENTER}"); //发送回车键
  412. //SendKeys.Send("{ENTER}");
  413. //END {END}
  414. //ENTER {ENTER} 或 ~
  415. //ESC {ESC}
  416. #endregion
  417. }
  418. #region 设置或获取execel.exe应用程序的其他显示式样
  419. /// <summary>
  420. /// 测试学习用
  421. /// </summary>
  422. /// <returns></returns>
  423. public bool AppExcel_SelfCheck()
  424. {
  425. try
  426. {
  427. int x1 = GetCommandBars_Count();
  428. int X2 = GetMenuBars_Count();
  429. this.GetApp_ElseProperty();
  430. this.SetCell_Value(1, 1, "测试值");
  431. string s = (string)GetCell_Value(1, 1);
  432. if (s != null) { MessageBox.Show(s); }
  433. this.SetRangeArray_FontProperty_EG();
  434. string ss = GetRangeArray_FormatStyle("A1", "B5");
  435. if (ss != null) { MessageBox.Show(ss); }
  436. this.GetMenuBars_SerialNumber();
  437. this.SetSheet_hiddenSheet(2, false);
  438. return true;
  439. }
  440. catch (Exception ex)
  441. {
  442. MessageBox.Show("App自检有误!" + ex.Message);
  443. return false;
  444. }
  445. }
  446. /// <summary>
  447. /// 获取m_objApp 的  //Count //Name //Version
  448. /// </summary>
  449. public void GetApp_ElseProperty()
  450. {
  451. //*****************************
  452. //获取同一个excel进程中,打开的窗口数量总数
  453. object wbCount = m_objBooks.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, m_objBooks, null);
  454. Object oName = m_objApp.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, m_objApp, null);
  455. Object oVersion = m_objApp.GetType().InvokeMember("Version", BindingFlags.GetProperty, null, m_objApp, new object[0]);
  456. }
  457. /// <summary>
  458. /// 返回“数据输入”模式
  459. /// 处于“数据输入”模式时,仅可在当前选定区域的未锁定单元格中输入数据。Long 类型,可读写。
  460. /// </summary>
  461. /// <returns></returns>
  462. public object GetApp_DataEntryMode()
  463. {
  464. if (m_objApp == null) { return false; }
  465. if (m_objSheet == null) { return false; }
  466. this.SetApp_Exit_EditMode();
  467. try
  468. {
  469. object oAppDataEntryMode = m_objApp.GetType().InvokeMember("DataEntryMode", BindingFlags.GetProperty, null, m_objApp, null); //ok
  470. return oAppDataEntryMode;
  471. }
  472. catch (Exception ex)
  473. {
  474. MessageBox.Show("错误原因:" + ex.Message);
  475. return null;
  476. }
  477. }
  478. /// <summary>
  479. /// 设置“数据输入”模式
  480. /// 处于“数据输入”模式时,仅可在当前选定区域的未锁定单元格中输入数据。Long 类型,可读写。
  481. /// </summary>
  482. /// <param name="_bStyle"></param>
  483. /// <returns></returns>
  484. public bool SetApp_DataEntryMode(int _bStyle)
  485. {
  486. if (m_objApp == null) { return false; }
  487. if (m_objSheet == null) { return false; }
  488. this.SetApp_Exit_EditMode();
  489. try
  490. {
  491. object[] m_Parameters_set = new Object[1] { _bStyle };
  492. m_objApp.GetType().InvokeMember("DataEntryMode", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set);
  493. return true;
  494. }
  495. catch (Exception ex)
  496. {
  497. MessageBox.Show("错误原因:" + ex.Message);
  498. return false;
  499. }
  500. }
  501. /// <summary>
  502. /// 获取激活的ActiveWindow对象
  503. /// </summary>
  504. /// <returns></returns>
  505. public object GetApp_ActiveWindow()
  506. {
  507. if (m_objApp == null) { return false; }
  508. if (m_objSheet == null) { return false; }
  509. this.SetApp_Exit_EditMode();
  510. try
  511. {
  512. //选择当前激活的的Window
  513. object OActiveWindow = m_objApp.GetType().InvokeMember("ActiveWindow", BindingFlags.GetProperty, null, m_objApp, null); //ok
  514. return OActiveWindow;
  515. }
  516. catch (Exception ex)
  517. {
  518. MessageBox.Show("错误原因:" + ex.Message);
  519. return null;
  520. }
  521. }
  522. /// <summary>
  523. /// 获取激活的ActiveSheet对象
  524. /// </summary>
  525. /// <returns></returns>
  526. public object GetApp_ActiveSheet()
  527. {
  528. if (m_objApp == null) { return false; }
  529. if (m_objSheet == null) { return false; }
  530. this.SetApp_Exit_EditMode();
  531. try
  532. {
  533. //选择当前激活的的Sheet
  534. object OActiveSheet = m_objApp.GetType().InvokeMember("ActiveSheet", BindingFlags.GetProperty, null, m_objApp, null); //ok
  535. return OActiveSheet;
  536. }
  537. catch (Exception ex)
  538. {
  539. MessageBox.Show("错误原因:" + ex.Message);
  540. return null;
  541. }
  542. }
  543. /// <summary>
  544. /// 获取激活的ActiveCell对象
  545. /// </summary>
  546. /// <returns></returns>
  547. public object GetApp_ActiveCell()
  548. {
  549. if (m_objApp == null) { return false; }
  550. if (m_objSheet == null) { return false; }
  551. this.SetApp_Exit_EditMode();
  552. try
  553. {
  554. //选择当前激活的的Sheet
  555. object OActiveCell = m_objApp.GetType().InvokeMember("ActiveCell", BindingFlags.GetProperty, null, m_objApp, null); //ok
  556. return OActiveCell;
  557. }
  558. catch (Exception ex)
  559. {
  560. MessageBox.Show("错误原因:" + ex.Message);
  561. return null;
  562. }
  563. }
  564. /// <summary>
  565. /// 显示excel程序的界面
  566. /// </summary>
  567. /// <param name="_objApp"></param>
  568. /// <param name="_bVisibleAppForm"></param>
  569. private void SetApp_Visible(object _objApp, bool _bVisibleAppForm)
  570. {
  571. if (m_objApp == null) { return; }
  572. ////Return control of Excel to the user.
  573. //object[] m_Parameters_VisibleAppForm = new Object[1] { true };
  574. object[] m_Parameters_VisibleAppForm = new Object[1] { _bVisibleAppForm };
  575. _objApp.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, _objApp, m_Parameters_VisibleAppForm);
  576. ////单步调试不能使用以下该句,否则出错
  577. //m_objApp.GetType().InvokeMember("UserControl", BindingFlags.SetProperty, null, m_objApp, m_Parameters_VisibleAppForm);
  578. }
  579. /// <summary>
  580. /// 设置窗口的显示模式
  581. /// </summary>
  582. /// <param name="_bStyle"> // 1=xlNormal=正常显示 // 2=xlMinimized=最小化显示 // 3=xlMaximized=最大化显示 </param>
  583. /// <returns></returns>
  584. public bool SetApp_ExcelWindowState(int _bStyle)
  585. {
  586. if (m_objApp == null) { return false; }
  587. //参数
  588. // 1=xlNormal=正常显示 // 2=xlMinimized=最小化显示 // 3=xlMaximized=最大化显示
  589. try
  590. {
  591. object[] m_Parameters_set = new Object[1] { _bStyle };
  592. m_objApp.GetType().InvokeMember("Windowstate", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set);
  593. return true;
  594. }
  595. catch (Exception ex)
  596. {
  597. MessageBox.Show("错误原因:" + ex.Message);
  598. return false;
  599. }
  600. }
  601. /// <summary>
  602. /// 显示excel底部状态栏
  603. /// </summary>
  604. /// <param name="_bEnabled">true=显示,false=隐藏 (默认 false)</param>
  605. /// <returns></returns>
  606. public bool SetApp_DisplayStatusBar(bool _bEnabled)
  607. {
  608. if (m_objApp == null) { return false; }
  609. //m_objExcel.DisplayStatusBar = true; //默认 false 显示excel底部状态栏
  610. //m_objExcel.DisplayFormulaBar = false; //默认 true true = 显示录入状态栏,false = 不显示录入状态栏
  611. //m_objExcel.DisplayAlerts = false; //默认 true =在必要时将在代码运行期间显示警告消息。设置为 False 可跳过警告并选择默认值。
  612. ////当 DisplayAlerts 设置为 False 时,在关闭工作簿前 Excel 不会提示您保存,这样可能会导致丢失数据。
  613. //m_objExcel.DisplayFullScreen = false; //默认 false
  614. try
  615. {
  616. object[] m_Parameters_set_false = new Object[1] { _bEnabled };
  617. //object[] m_Parameters_set_true = new Object[1] { true };
  618. m_objApp.GetType().InvokeMember("DisplayStatusBar", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set_false);
  619. return true;
  620. }
  621. catch (Exception ex)
  622. {
  623. MessageBox.Show("错误原因:" + ex.Message);
  624. return false;
  625. }
  626. }
  627. /// <summary>
  628. /// 显示录入状态栏
  629. /// </summary>
  630. /// <param name="_bEnabled">true=显示,false=隐藏 (默认 true)</param>
  631. /// <returns></returns>
  632. public bool SetApp_DisplayFormulaBar(bool _bEnabled)
  633. {
  634. if (m_objApp == null) { return false; }
  635. //m_objExcel.DisplayStatusBar = true; //默认 false 显示excel底部状态栏
  636. //m_objExcel.DisplayFormulaBar = false; //默认 true true = 显示录入状态栏,false = 不显示录入状态栏
  637. //m_objExcel.DisplayAlerts = false; //默认 true =在必要时将在代码运行期间显示警告消息。设置为 False 可跳过警告并选择默认值。
  638. ////当 DisplayAlerts 设置为 False 时,在关闭工作簿前 Excel 不会提示您保存,这样可能会导致丢失数据。
  639. //m_objExcel.DisplayFullScreen = false; //默认 false
  640. try
  641. {
  642. object[] m_Parameters_set_false = new Object[1] { _bEnabled };
  643. //object[] m_Parameters_set_true = new Object[1] { true };
  644. m_objApp.GetType().InvokeMember("DisplayFormulaBar", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set_false);
  645. return true;
  646. }
  647. catch (Exception ex)
  648. {
  649. MessageBox.Show("错误原因:" + ex.Message);
  650. return false;
  651. }
  652. }
  653. /// <summary>
  654. /// true =在必要时将在代码运行期间显示警告消息。设置为 False 可跳过警告并选择默认值
  655. /// 当 DisplayAlerts 设置为 False 时,在关闭工作簿前 Excel 不会提示您保存,这样可能会导致丢失数据。
  656. /// </summary>
  657. /// <param name="_bEnabled">true=显示,false=隐藏 (默认 true)</param>
  658. /// <returns></returns>
  659. public bool SetApp_DisplayAlerts(bool _bEnabled)
  660. {
  661. if (m_objApp == null) { return false; }
  662. //m_objExcel.DisplayStatusBar = true; //默认 false 显示excel底部状态栏
  663. //m_objExcel.DisplayFormulaBar = false; //默认 true true = 显示录入状态栏,false = 不显示录入状态栏
  664. //m_objExcel.DisplayAlerts = false; //默认 true =在必要时将在代码运行期间显示警告消息。设置为 False 可跳过警告并选择默认值。
  665. ////当 DisplayAlerts 设置为 False 时,在关闭工作簿前 Excel 不会提示您保存,这样可能会导致丢失数据。
  666. //m_objExcel.DisplayFullScreen = false; //默认 false
  667. try
  668. {
  669. object[] m_Parameters_set_false = new Object[1] { _bEnabled };
  670. //object[] m_Parameters_set_true = new Object[1] { true };
  671. m_objApp.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set_false);
  672. return true;
  673. }
  674. catch (Exception ex)
  675. {
  676. MessageBox.Show("错误原因:" + ex.Message);
  677. return false;
  678. }
  679. }
  680. /// <summary>
  681. /// true =全屏 false=不全屏 (默认 false)
  682. /// </summary>
  683. /// <param name="_bEnabled">true =全屏 false=不全屏 (默认 false)</param>
  684. /// <returns></returns>
  685. public bool SetApp_DisplayFullScreen(bool _bEnabled)
  686. {
  687. if (m_objApp == null) { return false; }
  688. //m_objExcel.DisplayStatusBar = true; //默认 false 显示excel底部状态栏
  689. //m_objExcel.DisplayFormulaBar = false; //默认 true true = 显示录入状态栏,false = 不显示录入状态栏
  690. //m_objExcel.DisplayAlerts = false; //默认 true =在必要时将在代码运行期间显示警告消息。设置为 False 可跳过警告并选择默认值。
  691. ////当 DisplayAlerts 设置为 False 时,在关闭工作簿前 Excel 不会提示您保存,这样可能会导致丢失数据。
  692. //m_objExcel.DisplayFullScreen = false; //默认 false
  693. try
  694. {
  695. object[] m_Parameters_set_false = new Object[1] { _bEnabled };
  696. //object[] m_Parameters_set_true = new Object[1] { true };
  697. m_objApp.GetType().InvokeMember("DisplayFullScreen", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set_false);
  698. return true;
  699. }
  700. catch (Exception ex)
  701. {
  702. MessageBox.Show("错误原因:" + ex.Message);
  703. return false;
  704. }
  705. }
  706. /// <summary>
  707. /// 获取excel.exe的准备状态
  708. /// </summary>
  709. /// <returns></returns>
  710. public bool GetApp_Ready()
  711. {
  712. if (m_objApp == null) { return false; }
  713. try
  714. {
  715. bool bAppReady = (bool)m_objApp.GetType().InvokeMember("Ready", BindingFlags.GetProperty, null, m_objApp, null);
  716. return bAppReady;
  717. }
  718. catch (Exception ex)
  719. {
  720. MessageBox.Show("错误原因:" + ex.Message);
  721. return false;
  722. }
  723. }
  724. /// <summary>
  725. /// 获取 用户通过键盘和鼠标与Excel之间的交互的状态 true =可以交互 false=不能交互 (默认 true)
  726. /// </summary>
  727. /// <returns></returns>
  728. public bool GetApp_Interactive()
  729. {
  730. if (m_objApp == null) { return false; }
  731. if (m_objSheet == null) { return false; }
  732. this.SetApp_Exit_EditMode();
  733. try
  734. {
  735. bool bInteractive = (bool)m_objApp.GetType().InvokeMember("Interactive", BindingFlags.GetProperty, null, m_objApp, null);
  736. return bInteractive;
  737. }
  738. catch (Exception ex)
  739. {
  740. MessageBox.Show("错误原因:" + ex.Message);
  741. return false;
  742. }
  743. }
  744. /// <summary>
  745. /// 设置用户通过键盘和鼠标与Excel之间的交互 true =可以交互 false=不能交互 (默认 true)
  746. /// </summary>
  747. /// <param name="_bEnabled">true =可以交互 false=不能交互 (默认 true)</param>
  748. /// <returns></returns>
  749. public bool SetApp_Interactive(bool _bEnabled)
  750. {
  751. if (m_objApp == null) { return false; }
  752. if (m_objSheet == null) { return false; }
  753. this.SetApp_Exit_EditMode();
  754. try
  755. {
  756. object[] m_Parameters_set_false = new Object[1] { _bEnabled };
  757. //object[] m_Parameters_set_true = new Object[1] { true };
  758. m_objApp.GetType().InvokeMember("Interactive", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set_false);
  759. return true;
  760. }
  761. catch (Exception ex)
  762. {
  763. MessageBox.Show("错误原因:" + ex.Message);
  764. return false;
  765. }
  766. }
  767. /// <summary>
  768. /// 是否显示 禁止"键入需要帮助的问题 DisableAskAQuestionDropdown"
  769. /// </summary>
  770. /// <param name="_bDisable"></param>
  771. /// <returns></returns>
  772. public bool SetApp_DisableAskAQuestionDropdown(bool _bDisable)
  773. {
  774. if (m_objApp == null) { return false; }
  775. if (m_objSheet == null) { return false; }
  776. this.SetApp_Exit_EditMode();
  777. object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, null);
  778. try
  779. {
  780. m_objApp.GetType().InvokeMember("DisableAskAQuestionDropdown", BindingFlags.SetProperty, null, objCommandBars, new Object[1] { _bDisable });
  781. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  782. GC.GetTotalMemory(true);
  783. return true;
  784. }
  785. catch (Exception ex)
  786. {
  787. MessageBox.Show("错误原因:" + ex.Message);
  788. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  789. GC.GetTotalMemory(true);
  790. return false;
  791. }
  792. }
  793. /// <summary>
  794. /// 是否显示 禁止“用户自己定义菜单” DisableCustomize
  795. /// </summary>
  796. /// <param name="_bDisable"></param>
  797. /// <returns></returns>
  798. public bool SetApp_DisableCustomize(bool _bDisable) //
  799. {
  800. if (m_objApp == null) { return false; }
  801. if (m_objSheet == null) { return false; }
  802. this.SetApp_Exit_EditMode();
  803. object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, null);
  804. try
  805. {
  806. m_objApp.GetType().InvokeMember("DisableCustomize", BindingFlags.SetProperty, null, objCommandBars, new Object[1] { true });
  807. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  808. GC.GetTotalMemory(true);
  809. return true;
  810. }
  811. catch (Exception ex)
  812. {
  813. MessageBox.Show("错误原因:" + ex.Message);
  814. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  815. GC.GetTotalMemory(true);
  816. return false;
  817. }
  818. }
  819. /// <summary>
  820. /// 显示行号列标
  821. /// </summary>
  822. /// <param name="_bVisible">是否显示,false = 禁止显示</param>
  823. /// <returns>是否成功</returns>
  824. public bool SetApp_Display_DisplayHeadings(bool _bVisible)
  825. {
  826. if (m_objApp == null) { return false; }
  827. if (m_objSheet == null) { return false; }
  828. this.SetApp_Exit_EditMode();
  829. try
  830. {
  831. object[] m_Parameters_set_false = new Object[1] { _bVisible };
  832. //选择当前激活的
  833. object OActiveWindow = m_objApp.GetType().InvokeMember("ActiveWindow", BindingFlags.GetProperty, null, m_objApp, null); //ok
  834. m_objApp.GetType().InvokeMember("DisplayHeadings", BindingFlags.SetProperty, null, OActiveWindow, m_Parameters_set_false); //ok
  835. //object oActivatorSheet = m_objSheets.GetType().InvokeMember("ActiveSheet", BindingFlags.GetProperty, null, m_objSheets, null); //错误
  836. //m_objApp.GetType().InvokeMember("DisplayHeadings", BindingFlags.SetProperty, null, oActivatorSheet, m_Parameters_set_false);
  837. return true;
  838. }
  839. catch (Exception ex)
  840. {
  841. MessageBox.Show("错误原因:" + ex.Message);
  842. return false;
  843. }
  844. }
  845. /// <summary>
  846. /// .获取:直接在单元格中进行编辑的能力。如果为 False,则只能在公式栏内编辑单元格
  847. /// </summary>
  848. /// <returns></returns>
  849. public bool GetApp_EditDirectlyInCell()
  850. {
  851. if (m_objApp == null) { return false; }
  852. if (m_objSheet == null) { return false; }
  853. this.SetApp_Exit_EditMode();
  854. try
  855. {
  856. object XX = m_objApp.GetType().InvokeMember("EditDirectlyInCell ", BindingFlags.GetProperty, null, m_objApp, null);
  857. return (bool)XX;
  858. }
  859. catch (Exception ex)
  860. {
  861. MessageBox.Show("错误原因:" + ex.Message);
  862. return false;
  863. }
  864. }
  865. /// <summary>
  866. /// 设置:直接在单元格中进行编辑的能力。如果为 False,则只能在公式栏内编辑单元格
  867. /// </summary>
  868. /// <param name="_bEnabled"></param>
  869. /// <returns></returns>
  870. public bool SetApp_EditDirectlyInCell(bool _bEnabled)
  871. {
  872. if (m_objApp == null) { return false; }
  873. if (m_objSheet == null) { return false; }
  874. this.SetApp_Exit_EditMode();
  875. try
  876. {
  877. object[] m_Parameters_set_false = new Object[1] { _bEnabled };
  878. //object[] m_Parameters_set_true = new Object[1] { true };
  879. m_objApp.GetType().InvokeMember("EditDirectlyInCell ", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set_false);
  880. return true;
  881. }
  882. catch (Exception ex)
  883. {
  884. MessageBox.Show("错误原因:" + ex.Message);
  885. return false;
  886. }
  887. }
  888. /// <summary>
  889. /// 待用
  890. /// </summary>
  891. /// <param name="target"></param>
  892. /// <param name="name"></param>
  893. /// <param name="args"></param>
  894. /// <returns></returns>
  895. internal static object SetApp_PropertyInternational(object target, string name, params object[] args)
  896. {
  897. return target.GetType().InvokeMember(name,
  898. System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty |
  899. System.Reflection.BindingFlags.Public,
  900. null, target, args, new System.Globalization.CultureInfo(1033));
  901. }
  902. /// <summary>
  903. /// 待用
  904. /// </summary>
  905. /// <param name="target"></param>
  906. /// <param name="name"></param>
  907. /// <param name="args"></param>
  908. /// <returns></returns>
  909. internal static object GetApp_PropertyInternational(object target, string name, params object[] args)
  910. {
  911. return target.GetType().InvokeMember(name,
  912. System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty |
  913. System.Reflection.BindingFlags.Public,
  914. null, target, args, new System.Globalization.CultureInfo(1033));
  915. }
  916. #endregion
  917. #region 设置 菜单和命令的显示式样
  918. /// <summary>
  919. /// 得到CommandBars的总数
  920. /// </summary>
  921. /// <returns>CommandBars的总数</returns>
  922. public int GetCommandBars_Count()
  923. {
  924. if (m_objApp == null) { return 0; }
  925. object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, null); //Count
  926. try
  927. {
  928. int CommandBarsCount = (int)m_objApp.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, objCommandBars, null); //Count
  929. object[] m_Parameters_set = new Object[1] { false };
  930. //m_objApp.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set);
  931. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  932. GC.GetTotalMemory(true);
  933. return CommandBarsCount;
  934. }
  935. catch (Exception ex)
  936. {
  937. MessageBox.Show("错误原因:" + ex.Message);
  938. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  939. GC.GetTotalMemory(true);
  940. return 0;
  941. }
  942. }
  943. /// <summary>
  944. /// 得到MenuBars的总数
  945. /// </summary>
  946. /// <returns>MenuBars的总数</returns>
  947. public int GetMenuBars_Count()
  948. {
  949. if (m_objApp == null) { return 0; }
  950. object objMenuBars = m_objApp.GetType().InvokeMember("MenuBars", BindingFlags.GetProperty, null, m_objApp, null); //Count
  951. try
  952. {
  953. int CommandBarsCount = (int)m_objApp.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, objMenuBars, null); //Count
  954. System.Runtime.InteropServices.Marshal.ReleaseComObject(objMenuBars);
  955. GC.GetTotalMemory(true);
  956. return CommandBarsCount;
  957. }
  958. catch (Exception ex)
  959. {
  960. MessageBox.Show("错误!错误原因:" + ex.Message);
  961. System.Runtime.InteropServices.Marshal.ReleaseComObject(objMenuBars);
  962. GC.GetTotalMemory(true);
  963. return 0;
  964. }
  965. }
  966. /// <summary>
  967. /// 是否禁止 显示Worksheet Menu Bar 系统菜单
  968. /// </summary>
  969. /// <param name="_bEnabled"></param>
  970. /// <returns></returns>
  971. public bool SetMenuBars_SystemMenuBar_Enabled(bool _bEnabled) //
  972. {
  973. if (m_objApp == null) { return false; }
  974. if (m_objSheet == null) { return false; }
  975. this.SetApp_Exit_EditMode();
  976. object[] m_Parameters_Get = new Object[1] { "Worksheet Menu Bar" };
  977. object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, m_Parameters_Get);
  978. try
  979. {
  980. object X1 = objCommandBars.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, objCommandBars, null); //可以正确执行
  981. object X2 = objCommandBars.GetType().InvokeMember("Visible", BindingFlags.GetProperty, null, objCommandBars, null); //可以正确执行
  982. object X3 = objCommandBars.GetType().InvokeMember("Enabled", BindingFlags.GetProperty, null, objCommandBars, null); //可以正确执行
  983. //object X4 = m_objApp.GetType().InvokeMember("Caption", BindingFlags.GetProperty, null, se.Current, null); //不可以正确执行
  984. //Enabled //Visible
  985. object[] m_Parameters_set = new Object[1] { _bEnabled };
  986. objCommandBars.GetType().InvokeMember("Enabled", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set);
  987. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  988. GC.GetTotalMemory(true);
  989. return true;
  990. }
  991. catch (Exception ex)
  992. {
  993. MessageBox.Show("错误原因:" + ex.Message);
  994. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  995. GC.GetTotalMemory(true);
  996. return false;
  997. }
  998. }
  999. /// <summary>
  1000. /// 是否显示 显示Worksheet Menu Bar 系统菜单
  1001. /// </summary>
  1002. /// <param name="_bEnabled"></param>
  1003. /// <returns></returns>
  1004. public bool SetMenuBars_SystemMenuBar_Visible(bool _bEnabled) //
  1005. {
  1006. if (m_objApp == null) { return false; }
  1007. if (m_objSheet == null) { return false; }
  1008. this.SetApp_Exit_EditMode();
  1009. object[] m_Parameters_Get = new Object[1] { "Worksheet Menu Bar" };
  1010. object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, m_Parameters_Get);
  1011. try
  1012. {
  1013. object X1 = objCommandBars.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, objCommandBars, null); //可以正确执行
  1014. object X2 = objCommandBars.GetType().InvokeMember("Visible", BindingFlags.GetProperty, null, objCommandBars, null); //可以正确执行
  1015. object X3 = objCommandBars.GetType().InvokeMember("Enabled", BindingFlags.GetProperty, null, objCommandBars, null); //可以正确执行
  1016. //object X4 = m_objApp.GetType().InvokeMember("Caption", BindingFlags.GetProperty, null, se.Current, null); //不可以正确执行
  1017. //Enabled //Visible
  1018. object[] m_Parameters_set = new Object[1] { _bEnabled };
  1019. objCommandBars.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set);
  1020. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  1021. GC.GetTotalMemory(true);
  1022. return true;
  1023. }
  1024. catch (Exception ex)
  1025. {
  1026. MessageBox.Show("错误原因:" + ex.Message);
  1027. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  1028. GC.GetTotalMemory(true);
  1029. return false;
  1030. }
  1031. }
  1032. /// <summary>
  1033. /// 是否禁止 点击单元格的右健弹出的浮动菜单 disable the Cell menu (menu when you right click on a cell)
  1034. /// </summary>
  1035. /// <param name="_bEnabled"></param>
  1036. /// <returns></returns>
  1037. public bool SetCommandBar_Cell_Enabled(bool _bEnabled) //
  1038. {
  1039. if (m_objApp == null) { return false; }
  1040. if (m_objSheet == null) { return false; }
  1041. this.SetApp_Exit_EditMode();
  1042. object[] m_Parameters_Get = new Object[1] { "Cell" };
  1043. object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, m_Parameters_Get);
  1044. try
  1045. {
  1046. object[] m_Parameters_set = new Object[1] { _bEnabled };
  1047. objCommandBars.GetType().InvokeMember("Enabled", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set);
  1048. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  1049. GC.GetTotalMemory(true);
  1050. return true;
  1051. }
  1052. catch (Exception ex)
  1053. {
  1054. MessageBox.Show("错误原因:" + ex.Message);
  1055. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  1056. GC.GetTotalMemory(true);
  1057. return false;
  1058. }
  1059. }
  1060. /// <summary>
  1061. ///指定CommandBars名字 来设置其禁止与否 其中针对是否禁用  Worksheet Menu Bar 只能选择Enabled",不能Visible
  1062. /// </summary>
  1063. /// <param name="_strCommandBarsName">先得确定是否有CommandBars 的名字, 如 "Worksheet Menu Bar" "Standard" "Cell" </param>
  1064. /// <param name="_bEnabled">是否禁用</param>
  1065. /// <returns></returns>
  1066. public bool SetCommandBarName_Enabled(string _strCommandBarsName, bool _bEnabled)
  1067. {
  1068. if (m_objApp == null) { return false; }
  1069. if (m_objSheet == null) { return false; }
  1070. this.SetApp_Exit_EditMode();
  1071. object[] m_Parameters_Get = new Object[1] { _strCommandBarsName };
  1072. object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, m_Parameters_Get);
  1073. try
  1074. {
  1075. object[] m_Parameters_set = new Object[1] { _bEnabled };
  1076. objCommandBars.GetType().InvokeMember("Enabled", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set);
  1077. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  1078. GC.GetTotalMemory(true);
  1079. return true;
  1080. }
  1081. catch (Exception ex)
  1082. {
  1083. MessageBox.Show("错误原因:" + ex.Message);
  1084. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  1085. GC.GetTotalMemory(true);
  1086. return false;
  1087. }
  1088. }
  1089. /// <summary>
  1090. /// 指定CommandBars名字 来设置其显示与否 其中针对是否显示  Worksheet Menu Bar 只能选择Enabled",不能Visible
  1091. /// </summary>
  1092. /// <param name="_strCommandBarsName">先得确定是否有CommandBars的名字 如"Standard" "Formatting" "Envelope" "Task Pane" </param>
  1093. /// <param name="_bVisible"></param>
  1094. /// <returns></returns>
  1095. public bool SetCommandBarName_Visible(string _strCommandBarsName, bool _bVisible)
  1096. {
  1097. if (m_objApp == null) { return false; }
  1098. if (m_objSheet == null) { return false; }
  1099. this.SetApp_Exit_EditMode();
  1100. object[] m_Parameters_Get = new Object[1] { _strCommandBarsName };
  1101. object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, m_Parameters_Get);
  1102. try
  1103. {
  1104. if ((bool)objCommandBars.GetType().InvokeMember("Visible", BindingFlags.GetProperty, null, objCommandBars, null))
  1105. {
  1106. object[] m_Parameters_set = new Object[1] { _bVisible };
  1107. objCommandBars.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set);
  1108. }
  1109. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  1110. GC.GetTotalMemory(true);
  1111. return true;
  1112. }
  1113. catch (Exception ex)
  1114. {
  1115. MessageBox.Show("错误原因:" + ex.Message);
  1116. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  1117. GC.GetTotalMemory(true);
  1118. return false;
  1119. }
  1120. }
  1121. /// <summary>
  1122. /// 设置excel.exe应用程序的系统下拉菜单的Enabled 和Visible : true=(Enabled + Visible),false= (禁止 + 不可见)
  1123. /// </summary>
  1124. /// <param name="_bEnabled">true=(Enabled + Visible),false= (禁止 + 不可见)</param>
  1125. /// <returns></returns>
  1126. public void SetApp_ExcelSystemMenu_xiala(bool _bEnabled)
  1127. {
  1128. this.SetCommandBarName_Enabled("Worksheet Menu Bar", _bEnabled); ; //excel的系统主菜单
  1129. this.SetCommandBarName_Visible("Worksheet Menu Bar", _bEnabled); ; //excel的系统主菜单
  1130. }
  1131. /// <summary>
  1132. /// 设置excel.exe应用程序的标准命令工具栏(Standard)的Enabled 和Visible : true=(Enabled + Visible),false= (禁止 + 不可见)
  1133. /// </summary>
  1134. /// <param name="_bEnabled">true=(Enabled + Visible),false= (禁止 + 不可见)</param>
  1135. /// <returns></returns>
  1136. public void SetApp_ExcelSystemMenu_Standard(bool _bEnabled)
  1137. {
  1138. this.SetCommandBarName_Enabled("Standard", _bEnabled); ; //excel的系统主菜单
  1139. this.SetCommandBarName_Visible("Standard", _bEnabled); ; //excel的系统主菜单
  1140. }
  1141. /// <summary>
  1142. /// 设置excel.exe应用程序的标准格式化工具栏(Standard)的Enabled 和Visible : true=(Enabled + Visible),false= (禁止 + 不可见)
  1143. /// </summary>
  1144. /// <param name="_bEnabled">true=(Enabled + Visible),false= (禁止 + 不可见)</param>
  1145. /// <returns></returns>
  1146. public void SetApp_ExcelSystemMenu_Formatting(bool _bEnabled)
  1147. {
  1148. this.SetCommandBarName_Enabled("Formatting", _bEnabled); ; //excel的系统主菜单
  1149. this.SetCommandBarName_Visible("Formatting", _bEnabled); ; //excel的系统主菜单
  1150. }
  1151. /// <summary>
  1152. /// 指定CommandBars名字的ID号 来设置其显示与否 其中针对是否显示 如"文件"的ID为"30002" ,该方法尚在测试,不能正常使用
  1153. /// </summary>
  1154. /// <param name="_nCommandBarID">如"文件"的ID为"30002"</param>
  1155. /// <returns></returns>
  1156. public bool SetCommandBarID_Visible(int _nCommandBarID) //指定ID
  1157. {
  1158. if (m_objApp == null) { return false; }
  1159. if (m_objSheet == null) { return false; }
  1160. this.SetApp_Exit_EditMode();
  1161. try
  1162. {
  1163. //Standard //Menu Bar // Standard // Formatting // Ink // Envelope // Online Meeting // Print Preview // System // Tables // Task Pane
  1164. object[] m_Parameters_Get = new Object[1] { "Worksheet Menu Bar" }; //{ "Worksheet Menu Bar" }; //Standard
  1165. object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, m_Parameters_Get); //OK
  1166. m_Parameters_Get = new Object[1] { 30002 }; //可以这样定义,但后面不知道怎样调用方法
  1167. object objCommandBarControl = objCommandBars.GetType().InvokeMember("Controls", BindingFlags.GetProperty, null, objCommandBars, null); //OK
  1168. object[] m_Parameters_set = new Object[1] { false }; ////Enabled //Visible
  1169. objCommandBars.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set); //???
  1170. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBarControl);
  1171. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  1172. GC.GetTotalMemory(true);
  1173. return true;
  1174. }
  1175. catch (Exception ex)
  1176. {
  1177. MessageBox.Show("错误原因:" + ex.Message);
  1178. return false;
  1179. }
  1180. }
  1181. /// <summary>
  1182. /// 枚举CommandBars的名字 再禁止其使能 全部Enabled = false;
  1183. /// </summary>
  1184. /// <returns></returns>
  1185. public bool SetCommandBars_IEnumeratorCommandBarsName() //App_SetAppCommandBarsVisible //Standard //Menu Bar
  1186. {
  1187. if (m_objApp == null) { return false; }
  1188. if (m_objSheet == null) { return false; }
  1189. this.SetApp_Exit_EditMode();
  1190. try
  1191. {
  1192. object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, null);
  1193. object objCommandBarsGetEnumerator = objCommandBars.GetType().InvokeMember("GetEnumerator", BindingFlags.InvokeMethod, null, objCommandBars, null);
  1194. string strCommandBarsName = "";
  1195. System.Collections.IEnumerator se = (System.Collections.IEnumerator)objCommandBarsGetEnumerator;
  1196. while (se.MoveNext())
  1197. {
  1198. object X1 = objCommandBars.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, se.Current, null); //可以正确执行
  1199. object X2 = objCommandBars.GetType().InvokeMember("Visible", BindingFlags.GetProperty, null, se.Current, null); //可以正确执行
  1200. object X3 = objCommandBars.GetType().InvokeMember("Enabled", BindingFlags.GetProperty, null, se.Current, null); //可以正确执行
  1201. //object X4 = m_objApp.GetType().InvokeMember("Caption", BindingFlags.GetProperty, null, se.Current, null); //不可以正确执行
  1202. strCommandBarsName += (string)X1 + " Visible===" + X2.ToString() + " Enabled===" + X3.ToString() + "\r\n";
  1203. if ((bool)X2)
  1204. {
  1205. if ((bool)X3)
  1206. {
  1207. SetCommandBarName_Enabled(X1.ToString(), false); //禁止
  1208. }
  1209. }
  1210. }
  1211. //MessageBox.Show(strCommandBarsName); //调试用,察看CommandBars的名字和状态
  1212. //SuperTools.FileTools.StringToSaveLogFile(strCommandBarsName, false);
  1213. objCommandBarsGetEnumerator = null;
  1214. System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
  1215. GC.GetTotalMemory(true);
  1216. return true;
  1217. }
  1218. catch (Exception ex)
  1219. {
  1220. MessageBox.Show("错误原因:" + ex.Message);
  1221. return false;
  1222. }
  1223. }
  1224. /// <summary>
  1225. /// 枚举MenuBars
  1226. /// </summary>
  1227. /// <returns></returns>
  1228. public bool GetMenuBars_SerialNumber() //App_SetAppCommandBarsVisible //Standard //Menu Bar
  1229. {
  1230. if (m_objApp == null) { return false; }
  1231. int x = GetMenuBars_Count();
  1232. try
  1233. {
  1234. //object[] m_Parameters_Get = new Object[1] { 30002 };
  1235. object objMenuBars = m_objApp.GetType().InvokeMember("MenuBars", BindingFlags.GetProperty, null, m_objApp, null); //  GetEnumerator
  1236. object objMenuBarsGetEnumerator = m_objApp.GetType().InvokeMember("GetEnumerator", BindingFlags.GetProperty, null, objMenuBars, null);
  1237. //object objMenuBars11 = m_objApp.GetType().InvokeMember("Worksheet Menu Bar", BindingFlags.GetProperty, null, objMenuBars, null);
  1238. string strCommandBarsName = "";
  1239. System.Collections.IEnumerator se = (System.Collections.IEnumerator)objMenuBarsGetEnumerator;
  1240. int i = 0;
  1241. while (se.MoveNext())
  1242. {
  1243. i = i + 1;
  1244. object X1 = "菜单" + i.ToString(); // se.Current.GetType().InvokeMember("ID", BindingFlags.GetProperty, null, se.Current, null); //不能正确执行
  1245. //object X2 = m_objApp.GetType().InvokeMember("ID", BindingFlags.GetProperty, null, se.Current, null); //不能正确执行
  1246. strCommandBarsName += X1.ToString() + "\r\n";
  1247. //object[] m_Parameters_set_1 = new Object[1] { false }; //Visible //Enabled
  1248. //m_objApp.GetType().InvokeMember("Visible", BindingFlags.SetPropert, null, se.Current, m_Parameters_set_1); //???
  1249. }
  1250. MessageBox.Show("枚举MenuBars如下:\r\n" + strCommandBarsName);
  1251. //System.Runtime.InteropServices.Marshal.ReleaseComObject(objMenuBarsGetEnumerator);
  1252. objMenuBarsGetEnumerator = null;
  1253. //System.Runtime.InteropServices.Marshal.ReleaseComObject(objMenuBars);
  1254. //GC.GetTotalMemory(true);
  1255. return true;
  1256. }
  1257. catch (Exception ex)
  1258. {
  1259. MessageBox.Show("错误原因:" + ex.Message);
  1260. return false;
  1261. }
  1262. }
  1263. #endregion
  1264. #region sheet 操作
  1265. /// <summary>
  1266. /// 获取sheets的总数
  1267. /// </summary>
  1268. /// <returns>sheets的总数</returns>
  1269. public int GetSheet_SheetsCount()
  1270. {
  1271. if (m_objApp == null) { return 0; }
  1272. if (m_objSheet == null) { return 0; }
  1273. this.SetApp_Exit_EditMode();
  1274. try
  1275. {
  1276. int SheetsCount = (int)m_objSheets.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, m_objSheets, null);
  1277. return SheetsCount;
  1278. }
  1279. catch (Exception ex)
  1280. {
  1281. MessageBox.Show("错误!错误原因:" + ex.Message);
  1282. return 0;
  1283. }
  1284. }
  1285. /// <summary>
  1286. /// 获取激活的sheet对象
  1287. /// </summary>
  1288. /// <returns></returns>
  1289. public object GetSheet_Active_Sheet()
  1290. {
  1291. if (m_objApp == null) { return null; }
  1292. if (m_objSheet == null) { return null; }
  1293. this.SetApp_Exit_EditMode();
  1294. try
  1295. {
  1296. //选择当前激活的的Window
  1297. object OActiveWindow = m_objApp.GetType().InvokeMember("ActiveWindow", BindingFlags.GetProperty, null, m_objApp, null); //ok
  1298. //选择当前激活的的Sheet
  1299. object OActiveSheet = m_objApp.GetType().InvokeMember("ActiveSheet", BindingFlags.GetProperty, null, OActiveWindow, null); //ok
  1300. return OActiveSheet;
  1301. }
  1302. catch (Exception ex)
  1303. {
  1304. MessageBox.Show("错误原因:" + ex.Message);
  1305. return null;
  1306. }
  1307. }
  1308. /// <summary>
  1309. /// 获取激活的sheet 的sheet 的名字
  1310. /// </summary>
  1311. /// <returns></returns>
  1312. public string GetSheet_ActiveSheetName()
  1313. {
  1314. if (m_objApp == null) { return string.Empty; }
  1315. if (m_objSheet == null) { return string.Empty; }
  1316. this.SetApp_Exit_EditMode();
  1317. object m_objActiveSheet = m_objApp.GetType().InvokeMember("ActiveSheet", BindingFlags.GetProperty, null, m_objApp, null);
  1318. if (m_objActiveSheet == null) { return ""; }
  1319. string SheetName;
  1320. try
  1321. {
  1322. SheetName = (string)m_objActiveSheet.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, m_objActiveSheet, null);
  1323. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objActiveSheet);
  1324. GC.GetTotalMemory(true);
  1325. return SheetName;
  1326. }
  1327. catch (Exception ex)
  1328. {
  1329. MessageBox.Show("错误原因:" + ex.Message);
  1330. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objActiveSheet);
  1331. GC.GetTotalMemory(true);
  1332. return string.Empty;
  1333. }
  1334. }
  1335. /// <summary>
  1336. /// 获取制定sheet的名字
  1337. /// </summary>
  1338. /// <param name="iNoSheet">sheet序号,从1开始</param>
  1339. /// <returns>sheet的名字</returns>
  1340. public string GetSheet_SheetName(int iNoSheet) //GetSheet_ActiveSheetName
  1341. {
  1342. if (m_objSheets == null) { return string.Empty; }
  1343. int SheetsCount = GetSheet_SheetsCount();
  1344. if (iNoSheet > SheetsCount || iNoSheet < 1)
  1345. {
  1346. return string.Empty;
  1347. }
  1348. object[] m_Parameters_set = new Object[1] { iNoSheet }; //第一个sheet:sheet1
  1349. object m_objSheet_1 = m_objSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, m_objSheets, m_Parameters_set);
  1350. string SheetName;
  1351. try
  1352. {
  1353. SheetName = (string)m_objSheet_1.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, m_objSheet_1, null);
  1354. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
  1355. GC.GetTotalMemory(true);
  1356. return SheetName;
  1357. }
  1358. catch (Exception ex)
  1359. {
  1360. MessageBox.Show("错误原因:" + ex.Message);
  1361. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
  1362. GC.GetTotalMemory(true);
  1363. return string.Empty;
  1364. }
  1365. }
  1366. /// <summary>
  1367. /// 改变Sheet的名字
  1368. /// </summary>
  1369. /// <param name="iNoSheet">Sheet序号,从1开始</param>
  1370. /// <param name="_SheetName">新名字</param>
  1371. /// <returns>是否正确返回</returns>
  1372. public bool SetSheet_ChangSheetName(int iNoSheet, string _SheetName) //
  1373. {
  1374. if (m_objSheets == null) { return false; }
  1375. int SheetsCount = GetSheet_SheetsCount();
  1376. if (iNoSheet > SheetsCount || iNoSheet < 1)
  1377. {
  1378. return false;
  1379. }
  1380. object[] m_Parameters_set = new Object[1] { iNoSheet }; //第一个sheet:sheet1
  1381. object m_objSheet_1 = m_objSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, m_objSheets, m_Parameters_set);
  1382. try
  1383. {
  1384. m_Parameters_set = new Object[1] { _SheetName };
  1385. m_objSheet_1.GetType().InvokeMember("Name", BindingFlags.SetProperty, null, m_objSheet_1, m_Parameters_set);
  1386. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
  1387. GC.GetTotalMemory(true);
  1388. return true;
  1389. }
  1390. catch (Exception ex)
  1391. {
  1392. MessageBox.Show("错误原因:" + ex.Message);
  1393. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
  1394. GC.GetTotalMemory(true);
  1395. return false;
  1396. }
  1397. }
  1398. /// <summary>
  1399. /// 根据sheet的表格序号,改变当前工作sheet
  1400. /// </summary>
  1401. /// <param name="iNoSheet">待激活的sheet序号,从1开始</param>
  1402. public bool SetSheet_ChangeActivateSheet(int iNoSheet)
  1403. {
  1404. if (m_objSheets == null) { return false; }
  1405. int SheetsCount = GetSheet_SheetsCount();
  1406. if (iNoSheet > SheetsCount || iNoSheet < 1)
  1407. {
  1408. return false;
  1409. }
  1410. object[] m_Parameters_ActivatorSheet = new Object[1] { iNoSheet }; //第一个sheet:sheet1
  1411. object m_objSheet_1 = m_objSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, m_objSheets, m_Parameters_ActivatorSheet);
  1412. try
  1413. {
  1414. m_objSheet_1.GetType().InvokeMember("Activate", BindingFlags.InvokeMethod, null, m_objSheet_1, null);
  1415. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
  1416. GC.GetTotalMemory(true);
  1417. return true;
  1418. }
  1419. catch (Exception ex)
  1420. {
  1421. MessageBox.Show("激活sheet序号错误!错误原因:" + ex.Message);
  1422. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
  1423. GC.GetTotalMemory(true);
  1424. return false;
  1425. }
  1426. }
  1427. /// <summary>
  1428. /// 只显示sheet1,其余的sheet全部隐藏
  1429. /// </summary>
  1430. /// <param name="bVisible">false = 显示,true =隐藏 </param>
  1431. /// <returns> </returns>
  1432. public bool SetSheet_DisplaySheet1_hiddenElseAllSheets(bool bVisible)
  1433. {
  1434. if (m_objSheets == null) { return false; }
  1435. try
  1436. {
  1437. int SheetsCount = GetSheet_SheetsCount();
  1438. for (int i = 2; i <= SheetsCount; i++) //保留第一个Sheet显示
  1439. {
  1440. this.SetSheet_hiddenSheet(i, bVisible);
  1441. }
  1442. return true;
  1443. }
  1444. catch (Exception ex)
  1445. {
  1446. MessageBox.Show("错误原因:" + ex.Message);
  1447. return false;
  1448. }
  1449. }
  1450. /// <summary>
  1451. /// 是否显示隐藏 sheet
  1452. /// </summary>
  1453. /// <param name="iNoSheet">sheet的序号</param>
  1454. /// <param name="_bVisible">false = 显示,true =隐藏 </param>
  1455. /// <returns></returns>
  1456. public bool SetSheet_hiddenSheet(int iNoSheet, bool _bVisible)
  1457. {
  1458. if (m_objSheets == null) { return false; }
  1459. int SheetsCount = GetSheet_SheetsCount();
  1460. if (iNoSheet > SheetsCount || iNoSheet < 1)
  1461. {
  1462. return false;
  1463. }
  1464. object[] m_Parameters_ActivatorSheet = new Object[1] { iNoSheet }; //第一个sheet:sheet1
  1465. object m_objSheet_1 = m_objSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, m_objSheets, m_Parameters_ActivatorSheet);
  1466. try
  1467. {
  1468. object[] m_Parameters_Set = new Object[1];
  1469. if (_bVisible)
  1470. {
  1471. m_Parameters_Set[0] = 2; //隐藏
  1472. }
  1473. else
  1474. {
  1475. m_Parameters_Set[0] = 1; //取消
  1476. }
  1477. m_objSheet_1.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, m_objSheet_1, m_Parameters_Set);
  1478. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
  1479. GC.GetTotalMemory(true);
  1480. return true;
  1481. }
  1482. catch (Exception ex)
  1483. {
  1484. MessageBox.Show("错误原因:" + ex.Message);
  1485. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
  1486. GC.GetTotalMemory(true);
  1487. return false;
  1488. }
  1489. }
  1490. #endregion
  1491. #region 单元格的读写操作
  1492. /// <summary>
  1493. /// 内部使用,获取激活单元格的属性
  1494. /// </summary>
  1495. /// <param name="_strPropertyName">激活单元格的名字</param>
  1496. /// <returns>激活单元格的值</returns>
  1497. internal object GetCell_ActiveCell_Property(string _strPropertyName)
  1498. {
  1499. if (m_objApp == null) { return null; }
  1500. if (m_objSheet == null) { return null; }
  1501. this.SetApp_Exit_EditMode();
  1502. object m_objActiveCell = m_objApp.GetType().InvokeMember("ActiveCell", BindingFlags.GetProperty, null, m_objApp, null);
  1503. if (m_objActiveCell == null) { return 0; }
  1504. try
  1505. {
  1506. object oPropertyValue = (int)m_objActiveCell.GetType().InvokeMember(_strPropertyName, BindingFlags.GetProperty, null, m_objActiveCell, null);
  1507. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objActiveCell);
  1508. GC.GetTotalMemory(true);
  1509. return oPropertyValue;
  1510. }
  1511. catch (Exception ex)
  1512. {
  1513. MessageBox.Show("错误原因:" + ex.Message);
  1514. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objActiveCell);
  1515. GC.GetTotalMemory(true);
  1516. return null;
  1517. }
  1518. }
  1519. /// <summary>
  1520. /// 得到激活单元格的列的序号,从1开始
  1521. /// </summary>
  1522. /// <returns></returns>
  1523. public int GetCell_ActiveCell_ColumnNumber() // object m_obj
  1524. {
  1525. int nColumnNumber = (int)this.GetCell_ActiveCell_Property("Column");
  1526. return nColumnNumber;
  1527. }
  1528. /// <summary>
  1529. /// 得到激活单元格的列名
  1530. /// </summary>
  1531. /// <returns></returns>
  1532. public string GetCell_ActiveCell_ColumnName()
  1533. {
  1534. int n1 = this.GetCell_ActiveCell_ColumnNumber();
  1535. string str1 = SuperTools.UC_EmbedExcelIntoWinFormNoDLL.Tool_NtoL(n1);
  1536. return str1;
  1537. }
  1538. /// <summary>
  1539. /// 得到激活单元格的行的序号,从1开始
  1540. /// </summary>
  1541. /// <returns></returns>
  1542. public int GetCell_ActiveCell_RowNumber()
  1543. {
  1544. int nRowNumber = (int)GetCell_ActiveCell_Property("Row");
  1545. return nRowNumber;
  1546. }
  1547. /// <summary>
  1548. /// 获取单元格的位置名字,如得到"B5"
  1549. /// </summary>
  1550. /// <returns></returns>
  1551. public string GetCell_ActiveCell_Name()
  1552. {
  1553. string strActiveCell_RowName = this.GetCell_ActiveCell_RowNumber().ToString();
  1554. string strActiveCell_ColumnName = this.GetCell_ActiveCell_ColumnName();
  1555. return strActiveCell_ColumnName + strActiveCell_RowName;
  1556. }
  1557. /// <summary>
  1558. /// Range位置,如:"A1"
  1559. /// </summary>
  1560. /// <param name="strRange"></param>
  1561. /// <returns></returns>
  1562. public bool SetCell_ActiveCell(string strRange)
  1563. {
  1564. if (m_objApp == null) { return false; }
  1565. if (m_objSheet == null) { return false; }
  1566. this.SetApp_Exit_EditMode();
  1567. try
  1568. {
  1569. //object[] Parameters_range = new object[2] { "A1", System.Reflection.Missing.Value };
  1570. //object[] Parameters_range = new object[2] { strRange, System.Reflection.Missing.Value };
  1571. object[] Parameters_range = new object[2];
  1572. Parameters_range[0] = strRange;
  1573. Parameters_range[1] = System.Reflection.Missing.Value;
  1574. object m_objRange = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_range);
  1575. if (m_objRange == null)
  1576. {
  1577. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  1578. }
  1579. m_objRange.GetType().InvokeMember("Activate", BindingFlags.InvokeMethod, null, m_objRange, null);
  1580. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRange);
  1581. GC.GetTotalMemory(true);
  1582. return true;
  1583. }
  1584. catch (Exception ex)
  1585. {
  1586. MessageBox.Show("写入错误!错误原因:" + ex.Message);
  1587. return false;
  1588. }
  1589. }
  1590. /// <summary>
  1591. /// 写Cells单元格的值
  1592. /// </summary>
  1593. /// <param name="x">第x行,Excel的起始列为1</param>
  1594. /// <param name="y">第y列,Excel的起始行为1</param>
  1595. /// <param name="strWriteValue">写入的数值</param>
  1596. /// <returns>bool,是否正确写入</returns>
  1597. public bool SetCell_Value(int x, int y, string strWriteValue)
  1598. {
  1599. if (m_objApp == null) { return false; }
  1600. if (m_objSheet == null) { return false; }
  1601. this.SetApp_Exit_EditMode();
  1602. try
  1603. {
  1604. object[] Parameters_Cells = new object[2] { x, y }; //第x行,第y列
  1605. object m_objCells = m_objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty, null, m_objSheet, Parameters_Cells);
  1606. if (m_objCells == null)
  1607. {
  1608. Console.WriteLine("出错啦: m_objCells == null,请检查Cells的设置。");
  1609. }
  1610. //向指定单元格填写内容值
  1611. object[] Parameters_WriteValue = new Object[1] { strWriteValue }; //文本值写到excel当中
  1612. m_objCells.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, m_objCells, Parameters_WriteValue);
  1613. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objCells);
  1614. GC.GetTotalMemory(true);
  1615. return true;
  1616. }
  1617. catch (Exception ex)
  1618. {
  1619. MessageBox.Show("写入错误!错误原因:" + ex.Message);
  1620. return false;
  1621. }
  1622. }
  1623. /// <summary>
  1624. /// 获取Cells单元格的值
  1625. /// </summary>
  1626. /// <param name="x">第x行,Excel的起始列为1</param>
  1627. /// <param name="y">第y列,Excel的起始行为1</param>
  1628. /// <returns>object</returns>
  1629. public object GetCell_Value(int x, int y)
  1630. {
  1631. if (m_objApp == null) { return null; }
  1632. if (m_objSheet == null) { return null; }
  1633. this.SetApp_Exit_EditMode();
  1634. object[] Parameters_Cells = new object[2] { x, y }; //第x行,第y列
  1635. object m_objCells = m_objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, m_objSheet, Parameters_Cells);
  1636. if (m_objCells == null)
  1637. {
  1638. Console.WriteLine("出错啦: Cells == null,请检查Cells的设置。");
  1639. }
  1640. object m_objCellsValue = m_objCells.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, m_objCells, new object[0]);
  1641. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objCells);
  1642. GC.GetTotalMemory(true);
  1643. return m_objCellsValue;
  1644. }
  1645. /// <summary>
  1646. /// 获取Cells单元格的值 ,并将该单元格的值转化为string的数据类型
  1647. /// </summary>
  1648. /// <param name="x">第x行,Excel的起始列为1</param>
  1649. /// <param name="y">第y列,Excel的起始行为1</param>
  1650. /// <returns>Cells单元格的本文值</returns>
  1651. public string GetCell_Value_toString(int x, int y)
  1652. {
  1653. object ob1 = this.GetCell_Value(x, y);
  1654. if (ob1 != null)
  1655. {
  1656. string ss = ob1.ToString();
  1657. return ss;
  1658. }
  1659. else
  1660. {
  1661. return "";
  1662. }
  1663. }
  1664. /// <summary>
  1665. /// 写Range单元格的值
  1666. /// </summary>
  1667. /// <param name="strRange">Range单元格位置,如"A1"</param>
  1668. /// <param name="strWriteValue"></param>
  1669. /// <returns></returns>
  1670. public bool SetRange_Value(string strRange, string strWriteValue)
  1671. {
  1672. if (m_objApp == null) { return false; }
  1673. if (m_objSheet == null) { return false; }
  1674. this.SetApp_Exit_EditMode();
  1675. try
  1676. {
  1677. //object[] Parameters_range = new object[2] { "A1", System.Reflection.Missing.Value };
  1678. //object[] Parameters_range = new object[2] { strRange, System.Reflection.Missing.Value };
  1679. object[] Parameters_range = new object[2];
  1680. Parameters_range[0] = strRange;
  1681. Parameters_range[1] = System.Reflection.Missing.Value;
  1682. object m_objRange = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_range);
  1683. if (m_objRange == null)
  1684. {
  1685. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  1686. }
  1687. //向指定单元格填写内容值
  1688. object[] Parameters_WriteValue = new Object[1] { strWriteValue }; //文本值写到excel当中
  1689. m_objRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, m_objRange, Parameters_WriteValue);
  1690. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRange);
  1691. GC.GetTotalMemory(true);
  1692. return true;
  1693. }
  1694. catch (Exception ex)
  1695. {
  1696. MessageBox.Show("写入错误!错误原因:" + ex.Message);
  1697. return false;
  1698. }
  1699. }
  1700. /// <summary>
  1701. /// 获取Range单元格的值
  1702. /// </summary>
  1703. /// <param name="strRange">Range位置,如:"A1"</param>
  1704. /// <returns>object</returns>
  1705. public object GetRange_Value(string strRange)
  1706. {
  1707. if (m_objApp == null) { return null; }
  1708. if (m_objSheet == null) { return null; }
  1709. this.SetApp_Exit_EditMode();
  1710. //object[] Parameters_range = new object[2] { "A1", System.Reflection.Missing.Value };
  1711. object[] Parameters_range = new object[2] { strRange, System.Reflection.Missing.Value };
  1712. object m_objRange = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, m_objSheet, Parameters_range);
  1713. if (m_objRange == null)
  1714. {
  1715. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  1716. }
  1717. object m_objRangeValue = m_objRange.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, m_objRange, new object[0]);
  1718. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRange);
  1719. GC.GetTotalMemory(true);
  1720. return m_objRangeValue;
  1721. }
  1722. /// <summary>
  1723. /// 获取Range单元格的值 ,并将该单元格的值转化为string的数据类型
  1724. /// </summary>
  1725. /// <param name="strRange">Range位置,如:"A1"</param>
  1726. /// <returns>Range单元格的本文值</returns>
  1727. public string GetRange_Value_toString(string strRange)
  1728. {
  1729. object ob1 = GetRange_Value(strRange);
  1730. if (ob1 != null)
  1731. {
  1732. string ss = ob1.ToString();
  1733. return ss;
  1734. }
  1735. else
  1736. {
  1737. return "";
  1738. }
  1739. }
  1740. /// <summary>
  1741. /// 将二维数组 写入 excel
  1742. /// </summary>
  1743. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  1744. /// <param name="_EndPoint">终止位置 如"B5"</param>
  1745. /// <param name="_Array_Value">写入的二维数组的值,可以是各种数据类型</param>
  1746. /// <returns>bool,是否正确写入</returns>
  1747. public bool SetRangeArray_Value(string _BeginPoint, string _EndPoint, object[,] _Array_Value)
  1748. {
  1749. if (m_objApp == null) { return false; }
  1750. if (m_objSheet == null) { return false; }
  1751. this.SetApp_Exit_EditMode();
  1752. try
  1753. {
  1754. //得到range数组
  1755. //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
  1756. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  1757. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  1758. if (m_objRangeArray == null)
  1759. {
  1760. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  1761. }
  1762. //************************
  1763. //得到写入值
  1764. Object[] ParametersArray_WriteValue = new Object[1];
  1765. ParametersArray_WriteValue[0] = _Array_Value; //赋值:数值类型=int
  1766. //******************
  1767. m_objRangeArray.GetType().InvokeMember("Value2", BindingFlags.SetProperty, null, m_objRangeArray, ParametersArray_WriteValue);
  1768. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  1769. GC.GetTotalMemory(true);
  1770. return true;
  1771. }
  1772. catch (Exception ex)
  1773. {
  1774. MessageBox.Show("写入错误!错误原因:" + ex.Message);
  1775. return false;
  1776. }
  1777. }
  1778. /// <summary>
  1779. /// 将二维数组 写入 excel的一个实例,写入不同的数据类型
  1780. /// </summary>
  1781. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  1782. /// <param name="_EndPoint">EndPoint">终止位置 如"B5"</param>
  1783. /// <param name="_myDataType">数据类型,如ypeof(int) typeof(String) typeof(bool) typeof(DateTime) typeof(double) </param>
  1784. /// <returns></returns>
  1785. public bool SetRangeArray_Value_EG(string _BeginPoint, string _EndPoint, System.Type _myDataType)
  1786. {
  1787. try
  1788. {
  1789. //************************
  1790. int BeginPoint_y = System.Convert.ToInt16(_BeginPoint.Substring(1, 1));
  1791. int EndPoint_y = System.Convert.ToInt16(_EndPoint.Substring(1, 1));
  1792. int rows = EndPoint_y - BeginPoint_y + 1;
  1793. //************************
  1794. string strBeginPoint_X = _BeginPoint.Substring(0, 1);
  1795. string strEndPoint_X = _EndPoint.Substring(0, 1);
  1796. int columns = strEndPoint_X[0] - strBeginPoint_X[0] + 1;
  1797. //************************
  1798. Object[,] EG_Array_WriteValue = new object[rows, columns];
  1799. #region 各种数据类型
  1800. switch (_myDataType.Name)
  1801. {
  1802. case "Int32": //typeof(double)
  1803. int[,] Array_int_Value = new int[rows, columns]; //赋值:数值类型=int //typeof(int)
  1804. for (int i = 0; i < rows; i++)
  1805. {
  1806. for (int j = 0; j < columns; j++)
  1807. {
  1808. Array_int_Value[i, j] = i + j;
  1809. }
  1810. }
  1811. Array.Copy(Array_int_Value, EG_Array_WriteValue, rows * columns);
  1812. break;
  1813. case "String": //typeof(string)
  1814. string[,] Array_string_Value = new string[rows, columns]; //赋值:数值类型=string
  1815. for (int i = 0; i < rows; i++)
  1816. {
  1817. for (int j = 0; j < columns; j++)
  1818. {
  1819. Array_string_Value[i, j] = i.ToString() + "<>" + j.ToString();
  1820. }
  1821. }
  1822. Array.Copy(Array_string_Value, EG_Array_WriteValue, rows * columns);
  1823. break;
  1824. case "DateTime":
  1825. DateTime[,] Array_DateTime_Value = new DateTime[rows, columns]; //赋值:数值类型=时间
  1826. for (int i = 0; i < rows; i++)
  1827. {
  1828. for (int j = 0; j < columns; j++)
  1829. {
  1830. Array_DateTime_Value[i, j] = DateTime.Now.Date; //取得当前系统时间
  1831. }
  1832. }
  1833. Array.Copy(Array_DateTime_Value, EG_Array_WriteValue, rows * columns);
  1834. break;
  1835. case "Boolean": //typeof(bool)
  1836. Boolean[,] Array_bool_Value = new Boolean[rows, columns]; //赋值:数值类型=Bool
  1837. for (int i = 0; i < rows; i++)
  1838. {
  1839. for (int j = 0; j < columns; j++)
  1840. {
  1841. Array_bool_Value[i, j] = true;
  1842. }
  1843. }
  1844. Array.Copy(Array_bool_Value, EG_Array_WriteValue, rows * columns);
  1845. break;
  1846. }
  1847. #endregion
  1848. //******************
  1849. SetRangeArray_Value(_BeginPoint, _EndPoint, EG_Array_WriteValue); //调用本类中的App_SetRangeArrayValue方法
  1850. return true; ;
  1851. //******************V
  1852. }
  1853. catch (Exception ex)
  1854. {
  1855. MessageBox.Show("写入二维数组示例错误!错误原因:" + ex.Message);
  1856. return false;
  1857. }
  1858. }
  1859. /// <summary>
  1860. /// 读取excel的一个范围到一个二维数组里面, 不同的数据类型
  1861. /// </summary>
  1862. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  1863. /// <param name="_EndPoint">终止位置 如"B5"</param>
  1864. /// <returns>object[,]</returns>
  1865. public object[,] GetRangeArray_Value(string _BeginPoint, string _EndPoint)
  1866. {
  1867. if (m_objApp == null) { return null; }
  1868. if (m_objSheet == null) { return null; }
  1869. this.SetApp_Exit_EditMode();
  1870. try
  1871. {
  1872. //得到range数组
  1873. //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
  1874. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  1875. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  1876. if (m_objRangeArray == null)
  1877. {
  1878. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  1879. }
  1880. //******************
  1881. object[,] m_objRangeArrayValue = (object[,])m_objRangeArray.GetType().InvokeMember("Value2", BindingFlags.GetProperty, null, m_objRangeArray, new object[0]);
  1882. //object[,] m_objRangeArrayValue = (object[,])m_objRangeArray.GetType().InvokeMember("Value2", BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty, null, m_objRangeArray, new object[0]);
  1883. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  1884. GC.GetTotalMemory(true);
  1885. //******************
  1886. int rows = m_objRangeArrayValue.GetLength(0); //获取m_objRangeArrayValue的行数
  1887. int columns = m_objRangeArrayValue.GetLength(1); //获取m_objRangeArrayValue的列数
  1888. object[,] param = new object[rows, columns]; //转化为起始为0的数组
  1889. Array.Copy(m_objRangeArrayValue, param, rows * columns); //临时结果,学习用
  1890. //******************
  1891. return m_objRangeArrayValue; // public object[,] App_GetRangeArrayValue(string _BeginPoint, string _EndPoint)
  1892. }
  1893. catch (Exception ex)
  1894. {
  1895. MessageBox.Show("读取excel的数组错误!错误原因:" + ex.Message);
  1896. return null;
  1897. }
  1898. }
  1899. /// <summary>
  1900. /// 設定值,指出文字是否會自動縮小以符合可用的栏宽?
  1901. /// </summary>
  1902. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  1903. /// <param name="_EndPoint">终止位置 如"B5"</param>
  1904. /// <param name="_bEnabled">true=自动适应栏宽,false=不自动适应栏宽(默认= false)</param>
  1905. /// <returns></returns>
  1906. public bool SetRangeArray_ShrinkToFit(string _BeginPoint, string _EndPoint, bool _bEnabled)
  1907. {
  1908. if (m_objApp == null) { return false; }
  1909. if (m_objSheet == null) { return false; }
  1910. this.SetApp_Exit_EditMode();
  1911. try
  1912. {
  1913. //得到range数组
  1914. //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
  1915. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  1916. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  1917. if (m_objRangeArray == null)
  1918. {
  1919. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  1920. }
  1921. //************************
  1922. //得到写入值
  1923. Object[] ParametersArray_WriteValue = new Object[1];
  1924. ParametersArray_WriteValue[0] = _bEnabled; //赋值:数值类型=int
  1925. //******************
  1926. m_objRangeArray.GetType().InvokeMember("ShrinkToFit", BindingFlags.SetProperty, null, m_objRangeArray, ParametersArray_WriteValue);
  1927. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  1928. GC.GetTotalMemory(true);
  1929. return true;
  1930. }
  1931. catch (Exception ex)
  1932. {
  1933. MessageBox.Show("写入错误!错误原因:" + ex.Message);
  1934. return false;
  1935. }
  1936. }
  1937. /// <summary>
  1938. /// 設定指出 NamedRange 控制項是否為鎖定的值。?
  1939. /// </summary>
  1940. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  1941. /// <param name="_EndPoint">终止位置 如"B5"</param>
  1942. /// <param name="_bEnabled">true=鎖定,false=不鎖定(默认= false)</param>
  1943. /// <returns></returns>
  1944. public bool SetRangeArray_Locked(string _BeginPoint, string _EndPoint, bool _bEnabled)
  1945. {
  1946. if (m_objApp == null) { return false; }
  1947. if (m_objSheet == null) { return false; }
  1948. this.SetApp_Exit_EditMode();
  1949. try
  1950. {
  1951. //得到range数组
  1952. //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
  1953. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  1954. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  1955. if (m_objRangeArray == null)
  1956. {
  1957. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  1958. }
  1959. //************************
  1960. //得到写入值
  1961. Object[] ParametersArray_WriteValue = new Object[1];
  1962. ParametersArray_WriteValue[0] = _bEnabled; //赋值:数值类型=int
  1963. //******************
  1964. m_objRangeArray.GetType().InvokeMember("Locked", BindingFlags.SetProperty, null, m_objRangeArray, ParametersArray_WriteValue);
  1965. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  1966. GC.GetTotalMemory(true);
  1967. return true;
  1968. }
  1969. catch (Exception ex)
  1970. {
  1971. MessageBox.Show("写入错误!错误原因:" + ex.Message);
  1972. return false;
  1973. }
  1974. }
  1975. /// <summary>
  1976. /// 获取 NamedRange 控制項是否為鎖定的值。?
  1977. /// </summary>
  1978. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  1979. /// <param name="_EndPoint">终止位置 如"B5"</param>
  1980. /// <returns></returns>
  1981. public bool GetRangeArray_Locked(string _BeginPoint, string _EndPoint)
  1982. {
  1983. if (m_objApp == null) { return false; }
  1984. if (m_objSheet == null) { return false; }
  1985. this.SetApp_Exit_EditMode();
  1986. try
  1987. {
  1988. //得到range数组
  1989. //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
  1990. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  1991. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  1992. if (m_objRangeArray == null)
  1993. {
  1994. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  1995. }
  1996. //************************
  1997. Object oLocked = m_objRangeArray.GetType().InvokeMember("Locked", BindingFlags.GetProperty, null, m_objRangeArray, null);
  1998. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  1999. GC.GetTotalMemory(true);
  2000. return (bool)oLocked;
  2001. }
  2002. catch (Exception ex)
  2003. {
  2004. MessageBox.Show("写入错误!错误原因:" + ex.Message);
  2005. return false;
  2006. }
  2007. }
  2008. /// <summary>
  2009. /// 读取excel的某一固定列中几行的数据到一个二维数组里面, 不同的数据类型
  2010. /// </summary>
  2011. /// <param name="x_ColumnName">excel列的名字,如"A" "B" "B"</param>
  2012. /// <param name="y1">该列的起始位置</param>
  2013. /// <param name="RowsCount">读取的行数</param>
  2014. /// <returns>System.Collections.ArrayList</returns>
  2015. public System.Collections.ArrayList GetRangeArray_Value_ArrayList(string x_ColumnName, int y1, int RowsCount)
  2016. {
  2017. string BeginPoint = x_ColumnName.ToUpper() + y1.ToString();
  2018. string EndPoint = x_ColumnName.ToUpper() + (y1 + RowsCount - 1).ToString();
  2019. object[,] ValueArray = GetRangeArray_Value(BeginPoint, EndPoint); //调用本类中的方法:App_GetRangeArrayValue
  2020. System.Collections.ArrayList aa = Tools_Array2ArrayList(ValueArray); //调用/调用本类中的静态方法:Tools_Array2ArrayList
  2021. return aa;
  2022. }
  2023. /// <summary>
  2024. /// 读取excel的某一固定行中几列的数据到一个二维数组里面, 不同的数据类型
  2025. /// </summary>
  2026. /// <param name="x_ColumnName_1">excel起始列的名字,如"A" "B" "B"</param>
  2027. /// <param name="x_ColumnName_2">excel终止列的名字,如"A" "B" "B"</param>
  2028. /// <param name="RowsNumber">读取的行的序号</param>
  2029. /// <returns>System.Collections.ArrayList </returns>
  2030. public System.Collections.ArrayList GetRangeArray_Value_ArrayList(string x_ColumnName_1, string x_ColumnName_2, int RowsNumber)
  2031. {
  2032. string BeginPoint = x_ColumnName_1.ToUpper() + RowsNumber.ToString();
  2033. string EndPoint = x_ColumnName_2.ToUpper() + RowsNumber.ToString();
  2034. object[,] ValueArray = GetRangeArray_Value(BeginPoint, EndPoint); //调用本类中的方法:App_GetRangeArrayValue
  2035. System.Collections.ArrayList aa = Tools_Array2ArrayList(ValueArray); //调用/调用本类中的静态方法:Tools_Array2ArrayList
  2036. return aa;
  2037. }
  2038. /// <summary>
  2039. /// 读取excel的某一固定列中几行的数据到一个二维数组里面, 不同的数据类型 转化为string[]
  2040. /// </summary>
  2041. /// <param name="x_ColumnName">excel列的名字,如"A" "B" "B"</param>
  2042. /// <param name="y1">该列的起始位置</param>
  2043. /// <param name="RowsCount">读取的行数</param>
  2044. /// <returns>string[]</returns>
  2045. public string[] GetRangeArray_Value_string(string x_ColumnName, int y1, int RowsCount)
  2046. {
  2047. string BeginPoint = x_ColumnName.ToUpper() + y1.ToString();
  2048. string EndPoint = x_ColumnName.ToUpper() + (y1 + RowsCount - 1).ToString();
  2049. object[,] ValueArray = GetRangeArray_Value(BeginPoint, EndPoint); //调用本类中的方法:App_GetRangeArrayValue
  2050. string[] cc = Tools_ConvertToStringArray(ValueArray);
  2051. return cc;
  2052. }
  2053. /// <summary>
  2054. /// 读取excel的某一固定行中几列的数据到一个二维数组里面, 不同的数据类型 转化为string[]
  2055. /// </summary>
  2056. /// <param name="x_ColumnName_1">excel起始列的名字,如"A" "B" "B"</param>
  2057. /// <param name="x_ColumnName_2">excel终止列的名字,如"A" "B" "B"</param>
  2058. /// <param name="RowsNumber">读取的行的序号</param>
  2059. /// <returns>string[]</returns>
  2060. public string[] GetRangeArray_Value_string(string x_ColumnName_1, string x_ColumnName_2, int RowsNumber)
  2061. {
  2062. string BeginPoint = x_ColumnName_1.ToUpper() + RowsNumber.ToString();
  2063. string EndPoint = x_ColumnName_2.ToUpper() + RowsNumber.ToString();
  2064. object[,] ValueArray = GetRangeArray_Value(BeginPoint, EndPoint); //调用本类中的方法:App_GetRangeArrayValue
  2065. //System.Collections.ArrayList aa = Tools_Array2ArrayList(ValueArray); //调用/调用本类中的静态方法:Tools_Array2ArrayList
  2066. //object[] bb = Tools_ArrayList2Array(aa);
  2067. string[] cc = Tools_ConvertToStringArray(ValueArray);
  2068. return cc;
  2069. }
  2070. /// <summary>
  2071. /// 将object[,]转换为ArrayList
  2072. /// </summary>
  2073. /// <param name="_object_Array_Value"></param>
  2074. /// <returns></returns>
  2075. public static System.Collections.ArrayList Tools_Array2ArrayList(object[,] _object_Array_Value)
  2076. {
  2077. System.Collections.ArrayList myArrayList = new System.Collections.ArrayList();
  2078. System.Collections.IEnumerator se = _object_Array_Value.GetEnumerator();
  2079. while (se.MoveNext())
  2080. {
  2081. myArrayList.Add(se.Current);
  2082. }
  2083. return myArrayList;
  2084. //System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
  2085. // ParaColumns.Add("ID|Int16"); //
  2086. // ParaColumns.Add("日期|DateTime"); // System.DateTime
  2087. // ParaColumns.Add("工资|Decimal"); //System.Decimal
  2088. }
  2089. /// <summary>
  2090. /// 将ArrayList转换为 object[,]
  2091. /// </summary>
  2092. /// <param name="_ArrayList"></param>
  2093. /// <returns></returns>
  2094. public static object[] Tools_ArrayList2Array(System.Collections.ArrayList _ArrayList)
  2095. {
  2096. object[] ValueArray = _ArrayList.ToArray();
  2097. return ValueArray;
  2098. }
  2099. /// <summary>
  2100. /// object[,]转化成为string[]
  2101. /// </summary>
  2102. /// <param name="values"></param>
  2103. /// <returns></returns>
  2104. private static string[] Tools_ConvertToStringArray(object[,] values)
  2105. {
  2106. string[] newArray = new string[values.Length];
  2107. int index = 0;
  2108. for (int i = values.GetLowerBound(0); i <= values.GetUpperBound(0); i++)
  2109. {
  2110. for (int j = values.GetLowerBound(1); j <= values.GetUpperBound(1); j++)
  2111. {
  2112. if (values.GetValue(i, j) == null)
  2113. {
  2114. newArray[index] = "";
  2115. }
  2116. else
  2117. {
  2118. newArray[index] = (string)values.GetValue(i, j).ToString();
  2119. }
  2120. index++;
  2121. }
  2122. }
  2123. return newArray;
  2124. }
  2125. //
  2126. /// <summary>
  2127. /// 判断字符是否
  2128. /// </summary>
  2129. /// <param name="anyString"></param>
  2130. /// <returns></returns>
  2131. public static bool Tools_IsNumeric(string anyString)
  2132. {
  2133. if (anyString == null)
  2134. {
  2135. anyString = "";
  2136. }
  2137. if (anyString.Length > 0)
  2138. {
  2139. double dummyOut = new double();
  2140. System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US", true);
  2141. return Double.TryParse(anyString, System.Globalization.NumberStyles.Any, cultureInfo.NumberFormat, out dummyOut);
  2142. }
  2143. else
  2144. {
  2145. return false;
  2146. }
  2147. }
  2148. /// <summary>
  2149. /// 设置Columns的属性:列最适应宽度
  2150. /// </summary>
  2151. /// <param name="_strColumnsPropertyName">Columns的属性名字</param>
  2152. /// <param name="_Parameters_Set">Columns的属性设置值</param>
  2153. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2154. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2155. /// <returns></returns>
  2156. internal bool SetRangeArray_RangeProperty_Columns(string _strColumnsPropertyName, object[] _Parameters_Set, string _BeginPoint, string _EndPoint)
  2157. {
  2158. if (m_objApp == null) { return false; }
  2159. if (m_objSheet == null) { return false; }
  2160. this.SetApp_Exit_EditMode();
  2161. //********************
  2162. //得到range数组
  2163. //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
  2164. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  2165. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  2166. if (m_objRangeArray == null)
  2167. {
  2168. Console.WriteLine("出错啦: m_objRangeArray == null,请检查range的设置。");
  2169. }
  2170. //Columns
  2171. object m_objRangeColumns = m_objRangeArray.GetType().InvokeMember("Columns", BindingFlags.GetProperty, null, m_objRangeArray, null);
  2172. if (m_objRangeColumns == null)
  2173. {
  2174. Console.WriteLine("出错啦: m_objRangeColumns == null,请检查range的设置。");
  2175. }
  2176. //********************
  2177. try
  2178. {
  2179. m_objRangeColumns.GetType().InvokeMember(_strColumnsPropertyName, BindingFlags.InvokeMethod, null, m_objRangeColumns, _Parameters_Set);
  2180. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeColumns);
  2181. GC.GetTotalMemory(true);
  2182. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  2183. GC.GetTotalMemory(true);
  2184. return true;
  2185. }
  2186. catch (Exception ex)
  2187. {
  2188. MessageBox.Show("错误!错误原因:" + ex.Message);
  2189. return false;
  2190. }
  2191. }
  2192. /// <summary>
  2193. /// 列最适应宽度
  2194. /// </summary>
  2195. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2196. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2197. /// <returns></returns>
  2198. public void SetRangeArray_RangeProperty_Columns_AutoFit(string _BeginPoint, string _EndPoint)
  2199. {
  2200. if (m_objSheet == null) { return; }
  2201. this.SetRangeArray_RangeProperty_Columns("AutoFit", null, _BeginPoint, _EndPoint);
  2202. }
  2203. /// <summary>
  2204. /// 设置Rows的属性:行最适应高度
  2205. /// </summary>
  2206. /// <param name="_strColumnsPropertyName">Rows的属性名字</param>
  2207. /// <param name="_Parameters_Set">Rows的属性设置值</param>
  2208. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2209. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2210. /// <returns></returns>
  2211. internal bool SetRangeArray_RangeProperty_Rows(string _strColumnsPropertyName, object[] _Parameters_Set, string _BeginPoint, string _EndPoint)
  2212. {
  2213. if (m_objApp == null) { return false; }
  2214. if (m_objSheet == null) { return false; }
  2215. this.SetApp_Exit_EditMode();
  2216. //********************
  2217. //得到range数组
  2218. //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
  2219. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  2220. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  2221. if (m_objRangeArray == null)
  2222. {
  2223. Console.WriteLine("出错啦: m_objRangeArray == null,请检查range的设置。");
  2224. }
  2225. //Columns
  2226. object m_objRangeRows = m_objRangeArray.GetType().InvokeMember("Rows", BindingFlags.GetProperty, null, m_objRangeArray, null);
  2227. if (m_objRangeRows == null)
  2228. {
  2229. Console.WriteLine("出错啦: m_objRangeColumns == null,请检查range的设置。");
  2230. }
  2231. //********************
  2232. try
  2233. {
  2234. m_objRangeRows.GetType().InvokeMember(_strColumnsPropertyName, BindingFlags.InvokeMethod, null, m_objRangeRows, _Parameters_Set);
  2235. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeRows);
  2236. GC.GetTotalMemory(true);
  2237. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  2238. GC.GetTotalMemory(true);
  2239. return true;
  2240. }
  2241. catch (Exception ex)
  2242. {
  2243. MessageBox.Show("错误!错误原因:" + ex.Message);
  2244. return false;
  2245. }
  2246. }
  2247. /// <summary>
  2248. /// 行最适应高度
  2249. /// </summary>
  2250. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2251. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2252. /// <returns></returns>
  2253. public void SetRangeArray_RangeProperty_Rows_AutoFit(string _BeginPoint, string _EndPoint)
  2254. {
  2255. if (m_objSheet == null) { return; }
  2256. this.SetRangeArray_RangeProperty_Rows("AutoFit", null, _BeginPoint, _EndPoint);
  2257. }
  2258. /// <summary>
  2259. /// 内部调用: 设置RangeArray属性
  2260. /// </summary>
  2261. /// <param name="_strRangePropertyName">设置RangeArray属性的名字</param>
  2262. /// <param name="_Parameters_Set">设置RangeArray属性的参数值</param>
  2263. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2264. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2265. /// <returns></returns>
  2266. internal bool SetRangeArray_Property(string _strRangePropertyName, object[] _Parameters_Set, string _BeginPoint, string _EndPoint)
  2267. {
  2268. if (m_objApp == null) { return false; }
  2269. if (m_objSheet == null) { return false; }
  2270. this.SetApp_Exit_EditMode();
  2271. //********************
  2272. //得到range数组
  2273. //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
  2274. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  2275. object m_objRangeArrayProperty = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  2276. if (m_objRangeArrayProperty == null)
  2277. {
  2278. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  2279. }
  2280. //********************
  2281. try
  2282. {
  2283. m_objRangeArrayProperty.GetType().InvokeMember(_strRangePropertyName, BindingFlags.SetProperty, null, m_objRangeArrayProperty, _Parameters_Set);
  2284. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayProperty);
  2285. GC.GetTotalMemory(true);
  2286. return true;
  2287. }
  2288. catch (Exception ex)
  2289. {
  2290. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayProperty);
  2291. GC.GetTotalMemory(true);
  2292. MessageBox.Show("错误!错误原因:" + ex.Message);
  2293. return false;
  2294. }
  2295. }
  2296. /// <summary>
  2297. /// 设置水平居中的参数 :2=靠左; 3=居中; 4=靠右
  2298. /// </summary>
  2299. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2300. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2301. /// <param name="_nHorizontalAlignment">水平居中的参数 :2=靠左; 3=居中; 4=靠右</param>
  2302. public void SetRangeArray_RangeProperty_HorizontalAlignment(string _BeginPoint, string _EndPoint, int _nHorizontalAlignment)
  2303. {
  2304. if (m_objSheet == null) { return; }
  2305. //水平参数:2=靠左; 3=居中; 4=靠右
  2306. object[] Parameters_Set = new Object[1] { _nHorizontalAlignment }; //HorizontalAlignment
  2307. this.SetRangeArray_Property("HorizontalAlignment", Parameters_Set, _BeginPoint, _EndPoint);
  2308. }
  2309. /// <summary>
  2310. /// 设置垂直居中的参数 :1=靠上 ;2=居中; 3=靠下;
  2311. /// </summary>
  2312. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2313. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2314. /// <param name="_nVerticalAlignment">垂直居中的参数 :1=靠上 ;2=居中; 3=靠下</param>
  2315. public void SetRangeArray_RangeProperty_VerticalAlignment(string _BeginPoint, string _EndPoint, int _nVerticalAlignment)
  2316. {
  2317. if (m_objSheet == null) { return; }
  2318. //垂直参数:1=靠上 ;2=居中; 3=靠下;
  2319. object[] Parameters_Set = new Object[1] { _nVerticalAlignment }; //HorizontalAlignment
  2320. this.SetRangeArray_Property("HorizontalAlignment", Parameters_Set, _BeginPoint, _EndPoint);
  2321. }
  2322. /// <summary>
  2323. /// 设置自动换行,或禁止
  2324. /// </summary>
  2325. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2326. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2327. /// <param name="_bWrap">自动换行=true ,禁止 =false </param>
  2328. public void SetRangeArray_RangeProperty_WrapText(string _BeginPoint, string _EndPoint, bool _bWrap)
  2329. {
  2330. if (m_objSheet == null) { return; }
  2331. object[] Parameters_Set = new Object[1] { _bWrap }; //
  2332. this.SetRangeArray_Property("WrapText", Parameters_Set, _BeginPoint, _EndPoint);
  2333. }
  2334. /// <summary>
  2335. /// 设置边框的线形
  2336. /// type:1=左边界;2=右边界;3=上边界;4=下边界;5=左上倾斜;6=右上倾斜(以上为对单元格的操作)
  2337. /// type:7=左边界;8=上边界;9=下边界;10=右边界;11=内部垂直边界;12=内部水平边界(以上为对区域的操作)
  2338. /// </summary>
  2339. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2340. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2341. /// <param name="_nBordersType">//type:1=左边界;2=右边界;3=上边界;4=下边界;5=左上倾斜;6=右上倾斜(以上为对单元格的操作) 7=左边界;8=上边界;9=下边界;10=右边界;11=内部垂直边界;12=内部水平边界(以上为对区域的操作)</param>
  2342. /// <param name="_nlinestyleValue">__nlinestyleValue:0 =无 1=细实(7=细实)、2=细虚、4=点虚、9=双细实线 </param>
  2343. /// <returns></returns>
  2344. public bool SetRangeArray_Borders_linestyle(string _BeginPoint, string _EndPoint, int _nBordersType, int _nlinestyleValue)
  2345. {
  2346. if (m_objApp == null) { return false; }
  2347. if (m_objSheet == null) { return false; }
  2348. this.SetApp_Exit_EditMode();
  2349. //_nBordersType: 1=左边界;2=右边界;3=上边界;4=下边界;5=左上倾斜;6=右上倾斜(以上为对单元格的操作)
  2350. // 7=左边界;8=上边界;9=下边界;10=右边界;11=内部垂直边界;12=内部水平边界(以上为对区域的操作)
  2351. //_nlinestyleValue:0 =无 1=细实(7=细实)、2=细虚、4=点虚、9=双细实线
  2352. //public enum XlLineStyle
  2353. //{
  2354. // xlLineStyleNone = -4142,
  2355. // xlDouble = -4119,
  2356. // xlDot = -4118,
  2357. // xlDash = -4115,
  2358. // xlContinuous = 1,
  2359. // xlDashDot = 4,
  2360. // xlDashDotDot = 5,
  2361. // xlSlantDashDot = 13,
  2362. //}
  2363. //********************
  2364. //得到range数组
  2365. //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
  2366. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  2367. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  2368. if (m_objRangeArray == null)
  2369. {
  2370. Console.WriteLine("出错啦: m_objRangeArray == null,请检查range的设置。");
  2371. }
  2372. object[] Parameters_BordersType = new Object[1] { _nBordersType };
  2373. object m_objRangeArrayBorders = m_objRangeArray.GetType().InvokeMember("Borders", BindingFlags.GetProperty, null, m_objRangeArray, Parameters_BordersType);
  2374. if (m_objRangeArrayBorders == null)
  2375. {
  2376. Console.WriteLine("出错啦: m_objRangeArrayProperty == null,请检查range的设置。");
  2377. }
  2378. //********************
  2379. try
  2380. {
  2381. object[] Parameters_BordersValue = new Object[1] { _nlinestyleValue };
  2382. m_objRangeArrayBorders.GetType().InvokeMember("linestyle", BindingFlags.SetProperty, null, m_objRangeArrayBorders, Parameters_BordersValue);
  2383. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayBorders); //一定要注释,否则出错
  2384. GC.GetTotalMemory(true);
  2385. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  2386. GC.GetTotalMemory(true);
  2387. return true;
  2388. }
  2389. catch (Exception ex)
  2390. {
  2391. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayBorders); //一定要注释,否则出错
  2392. GC.GetTotalMemory(true);
  2393. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  2394. GC.GetTotalMemory(true);
  2395. MessageBox.Show("错误!错误原因:" + ex.Message);
  2396. return false;
  2397. }
  2398. }
  2399. /// <summary>
  2400. /// 设置区域内单元格四周边的边框的边界线
  2401. /// </summary>
  2402. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2403. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2404. /// <param name="_nlinestyleValue">linestyleValue:0 =无 1=细实(7=细实)、2=细虚、4=点虚、9=双细实线</param>
  2405. public void SetCell_Borders_All_linestyle(string _BeginPoint, string _EndPoint, int _nlinestyleValue)
  2406. {
  2407. if (m_objSheet == null) { return; }
  2408. this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 1, _nlinestyleValue); //左边界
  2409. this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 2, _nlinestyleValue); //右边界
  2410. this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 3, _nlinestyleValue); //上边界
  2411. this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 4, _nlinestyleValue); //下边界
  2412. this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 7, _nlinestyleValue); //左边界
  2413. this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 8, _nlinestyleValue); //右边界
  2414. this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 9, _nlinestyleValue); //上边界
  2415. this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 10, _nlinestyleValue); //下边界
  2416. }
  2417. /// <summary>
  2418. /// 设置边框的边界线的厚度
  2419. /// type:1=左边界;2=右边界;3=上边界;4=下边界;5=左上倾斜;6=右上倾斜(以上为对单元格的操作)
  2420. /// type:7=左边界;8=上边界;9=下边界;10=右边界;11=内部垂直边界;12=内部水平边界(以上为对区域的操作)
  2421. /// </summary>
  2422. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2423. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2424. /// <param name="_nBordersType">type:1=左边界;2=右边界;3=上边界;4=下边界;5=左上倾斜;6=右上倾斜(以上为对单元格的操作) 7=左边界;8=上边界;9=下边界;10=右边界;11=内部垂直边界;12=内部水平边界(以上为对区域的操作)</param>
  2425. /// <param name="_nBordersValue">val:0无边界线;然后1、2、3、4依次边界线加粗</param>
  2426. /// <returns></returns>
  2427. public bool SetRangeArray_Borders_Weight(string _BeginPoint, string _EndPoint, int _nBordersType, int _nBordersValue)
  2428. {
  2429. if (m_objApp == null) { return false; }
  2430. if (m_objSheet == null) { return false; }
  2431. this.SetApp_Exit_EditMode();
  2432. //_nBordersType: 1=左边界;2=右边界;3=上边界;4=下边界;5=左上倾斜;6=右上倾斜(以上为对单元格的操作)
  2433. // 7=左边界;8=上边界;9=下边界;10=右边界;11=内部垂直边界;12=内部水平边界(以上为对区域的操作)
  2434. //_nBordersValue:0无边界线;然后1、2、3、4依次边界线加粗
  2435. //public enum XlBorderWeight
  2436. //{
  2437. // xlMedium = -4138,
  2438. // xlHairline = 1,
  2439. // xlThin = 2,
  2440. // xlThick = 4,
  2441. //}
  2442. //********************
  2443. //得到range数组
  2444. //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
  2445. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  2446. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  2447. if (m_objRangeArray == null)
  2448. {
  2449. Console.WriteLine("出错啦: m_objRangeArray == null,请检查range的设置。");
  2450. }
  2451. object[] Parameters_BordersType = new Object[1] { _nBordersType };
  2452. object m_objRangeArrayBorders = m_objRangeArray.GetType().InvokeMember("Borders", BindingFlags.GetProperty, null, m_objRangeArray, Parameters_BordersType);
  2453. if (m_objRangeArrayBorders == null)
  2454. {
  2455. Console.WriteLine("出错啦: m_objRangeArrayBorders == null,请检查range的设置。");
  2456. }
  2457. //********************
  2458. try
  2459. {
  2460. object[] Parameters_BordersValue = new Object[1] { _nBordersValue };
  2461. m_objRangeArrayBorders.GetType().InvokeMember("Weight", BindingFlags.SetProperty, null, m_objRangeArrayBorders, Parameters_BordersValue);
  2462. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayBorders); //一定要注释,否则出错
  2463. GC.GetTotalMemory(true);
  2464. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  2465. GC.GetTotalMemory(true);
  2466. return true;
  2467. }
  2468. catch (Exception ex)
  2469. {
  2470. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayBorders); //一定要注释,否则出错
  2471. GC.GetTotalMemory(true);
  2472. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  2473. GC.GetTotalMemory(true);
  2474. MessageBox.Show("错误!错误原因:" + ex.Message);
  2475. return false;
  2476. }
  2477. }
  2478. /// <summary>
  2479. /// 设置区域内单元格四周边的边框的边界线的厚度
  2480. /// </summary>
  2481. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2482. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2483. /// <param name="_nBordersValue">val:0无边界线;然后1、2、3、4依次边界线加粗 </param>
  2484. public void SetCell_Borders_All_Weight(string _BeginPoint, string _EndPoint, int _nBordersValue)
  2485. {
  2486. if (m_objSheet == null) { return; }
  2487. this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 1, _nBordersValue); //左边界
  2488. this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 2, _nBordersValue); //右边界
  2489. this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 3, _nBordersValue); //上边界
  2490. this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 4, _nBordersValue); //下边界
  2491. this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 7, _nBordersValue); //左边界
  2492. this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 8, _nBordersValue); //右边界
  2493. this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 9, _nBordersValue); //上边界
  2494. this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 10, _nBordersValue); //下边界
  2495. }
  2496. /// <summary>
  2497. /// 内部调用,设置字体的属性
  2498. /// </summary>
  2499. /// <param name="_strFontPropertyName">字体属性的名字</param>
  2500. /// <param name="_Parameters_Set">字体属性的值</param>
  2501. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2502. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2503. /// <returns></returns>
  2504. internal bool SetRangeArray_Font(string _strFontPropertyName, object[] _Parameters_Set, string _BeginPoint, string _EndPoint)
  2505. {
  2506. if (m_objApp == null) { return false; }
  2507. if (m_objSheet == null) { return false; }
  2508. this.SetApp_Exit_EditMode();
  2509. //********************
  2510. //得到range数组
  2511. //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
  2512. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  2513. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  2514. object m_objRangeArrayFont = m_objRangeArray.GetType().InvokeMember("Font", BindingFlags.GetProperty, null, m_objRangeArray, null);
  2515. if (m_objRangeArray == null)
  2516. {
  2517. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  2518. }
  2519. //********************
  2520. try
  2521. {
  2522. m_objRangeArrayFont.GetType().InvokeMember(_strFontPropertyName, BindingFlags.SetProperty, null, m_objRangeArrayFont, _Parameters_Set);
  2523. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayFont); //一定要注释,否则出错
  2524. GC.GetTotalMemory(true);
  2525. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  2526. GC.GetTotalMemory(true);
  2527. return true;
  2528. }
  2529. catch (Exception ex)
  2530. {
  2531. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayFont); //一定要注释,否则出错
  2532. GC.GetTotalMemory(true);
  2533. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  2534. GC.GetTotalMemory(true);
  2535. MessageBox.Show("错误!错误原因:" + ex.Message);
  2536. return false;
  2537. }
  2538. }
  2539. /// <summary>
  2540. /// 设置前景色
  2541. /// </summary>
  2542. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2543. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2544. /// <param name="_nColor">1 =黑色 2 =白色 3 =红色 4 =绿 5 =蓝色 6 =黄色 7=紫红色</param>
  2545. /// <returns></returns>
  2546. public void SetRangeArray_FontProperty_ColorIndex(string _BeginPoint, string _EndPoint, int _nColor)
  2547. {
  2548. //1 =黑色 2 =白色 3 =红色 4 =绿 5 =蓝色 6 =黄色 7=紫红色
  2549. object[] Parameters_Set = new Object[1] { _nColor };
  2550. this.SetRangeArray_Font("ColorIndex", Parameters_Set, _BeginPoint, _EndPoint);
  2551. }
  2552. /// <summary>
  2553. /// 设置字号大小
  2554. /// </summary>
  2555. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2556. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2557. /// <param name="_nSize">字号,如12;14;18;32;48</param>
  2558. public void SetRangeArray_FontProperty_Size(string _BeginPoint, string _EndPoint, int _nSize)
  2559. {
  2560. object[] Parameters_Set = new Object[1] { _nSize };
  2561. this.SetRangeArray_Font("Size", Parameters_Set, _BeginPoint, _EndPoint);
  2562. }
  2563. /// <summary>
  2564. /// 设置字体
  2565. /// </summary>
  2566. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2567. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2568. /// <param name="_strName">字体的名字,如 "宋体"</param>
  2569. public void SetRangeArray_FontProperty_Name(string _BeginPoint, string _EndPoint, string _strName)
  2570. {
  2571. object[] Parameters_Set = new Object[1] { _strName };
  2572. this.SetRangeArray_Font("Name", Parameters_Set, _BeginPoint, _EndPoint);
  2573. }
  2574. /// <summary>
  2575. /// 设置是否黑体
  2576. /// </summary>
  2577. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2578. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2579. /// <param name="_bBold">是否黑体 true = 黑体</param>
  2580. public void SetRangeArray_FontProperty_Bold(string _BeginPoint, string _EndPoint, bool _bBold)
  2581. {
  2582. object[] Parameters_Set = new Object[1] { _bBold };
  2583. this.SetRangeArray_Font("Bold", Parameters_Set, _BeginPoint, _EndPoint);
  2584. }
  2585. /// <summary>
  2586. /// 设置是否下划线
  2587. /// </summary>
  2588. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2589. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2590. /// <param name="_bUnderline">是否下划线 true = 加下划线</param>
  2591. public void SetRangeArray_FontProperty_Underline(string _BeginPoint, string _EndPoint, bool _bUnderline)
  2592. {
  2593. object[] Parameters_Set = new Object[1] { _bUnderline };
  2594. this.SetRangeArray_Font("Underline", Parameters_Set, _BeginPoint, _EndPoint);
  2595. }
  2596. /// <summary>
  2597. /// 设置是否斜体
  2598. /// </summary>
  2599. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2600. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2601. /// <param name="_bItalic">是否斜体 true = 斜体</param>
  2602. public void SetRangeArray_FontProperty_Italic(string _BeginPoint, string _EndPoint, bool _bItalic)
  2603. {
  2604. object[] Parameters_Set = new Object[1] { _bItalic };
  2605. this.SetRangeArray_Font("Italic", Parameters_Set, _BeginPoint, _EndPoint);
  2606. }
  2607. /// <summary>
  2608. /// 设置属性举例,设置成为 斜体 下划线 黑体 隶书 字号 =18 前景色 =红色 背景色= 黄色
  2609. /// </summary>
  2610. public void SetRangeArray_FontProperty_EG() //
  2611. {
  2612. this.SetRangeArray_FontProperty_Bold("A1", "E8", true);
  2613. this.SetRangeArray_FontProperty_ColorIndex("A1", "E8", 3); //前景色 =红色
  2614. this.SetRangeArray_FontProperty_Italic("A1", "E8", true);
  2615. this.SetRangeArray_FontProperty_Name("A1", "E8", "隶书");
  2616. this.SetRangeArray_FontProperty_Size("A1", "E8", 72);
  2617. this.SetRangeArray_FontProperty_Underline("A1", "E8", true);
  2618. this.SetRangeArray_Property_BackGroundColor("A1", "E8", 7);
  2619. }
  2620. /// <summary>
  2621. /// 设置背景色
  2622. /// </summary>
  2623. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2624. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2625. /// <param name="_nColor">1 =黑色 2 =白色 3 =红色 4 =绿 5 =蓝色 6 =黄色 7=紫红色</param>
  2626. /// <returns></returns>
  2627. public bool SetRangeArray_Property_BackGroundColor(string _BeginPoint, string _EndPoint, int _nColor) //
  2628. {
  2629. if (m_objApp == null) { return false; }
  2630. if (m_objSheet == null) { return false; }
  2631. this.SetApp_Exit_EditMode();
  2632. //********************
  2633. //得到range数组
  2634. //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
  2635. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  2636. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  2637. object m_objRangeArrayFont = m_objRangeArray.GetType().InvokeMember("Interior", BindingFlags.GetProperty, null, m_objRangeArray, null);
  2638. if (m_objRangeArray == null)
  2639. {
  2640. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  2641. }
  2642. //********************
  2643. try
  2644. {
  2645. //*****************************
  2646. //objRange1.Interior.ColorIndex = "5"; //背景色:5=蓝色
  2647. //***************************************************
  2648. object[] Parameters_Set = new Object[1] { _nColor };
  2649. m_objApp.GetType().InvokeMember("ColorIndex", BindingFlags.SetProperty, null, m_objRangeArrayFont, Parameters_Set);
  2650. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayFont); //一定要注释,否则出错
  2651. GC.GetTotalMemory(true);
  2652. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  2653. GC.GetTotalMemory(true);
  2654. return true;
  2655. }
  2656. catch (Exception ex)
  2657. {
  2658. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayFont); //一定要注释,否则出错
  2659. GC.GetTotalMemory(true);
  2660. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  2661. GC.GetTotalMemory(true);
  2662. MessageBox.Show("错误!错误原因:" + ex.Message);
  2663. return false;
  2664. }
  2665. }
  2666. /// <summary>
  2667. /// 得到有效行个数
  2668. /// </summary>
  2669. /// <returns></returns>
  2670. public int GetRange_UsedRangeRowsCount()
  2671. {
  2672. if (m_objApp == null) { return 0; }
  2673. if (m_objSheet == null) { return 0; }
  2674. this.SetApp_Exit_EditMode();
  2675. try
  2676. {
  2677. object m_objUsedRange = m_objSheet.GetType().InvokeMember("UsedRange", BindingFlags.GetProperty, null, m_objSheet, null);
  2678. if (m_objUsedRange == null)
  2679. {
  2680. Console.WriteLine("出错啦: UsedRange == null。");
  2681. }
  2682. object m_objUsedRangeRows = m_objUsedRange.GetType().InvokeMember("Rows", BindingFlags.GetProperty, null, m_objUsedRange, null);
  2683. int UsedRangeRowsCount = (int)m_objUsedRangeRows.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, m_objUsedRangeRows, null);
  2684. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objUsedRangeRows); //一定要注释,否则出错
  2685. GC.GetTotalMemory(true);
  2686. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objUsedRange);
  2687. GC.GetTotalMemory(true);
  2688. return UsedRangeRowsCount;
  2689. }
  2690. catch (Exception ex)
  2691. {
  2692. GC.GetTotalMemory(true);
  2693. MessageBox.Show("读取GetRange_UsedRangeRowsCount错误!错误原因:" + ex.Message);
  2694. return 0;
  2695. }
  2696. }
  2697. /// <summary>
  2698. /// 得到有效列的个数
  2699. /// </summary>
  2700. /// <returns></returns>
  2701. public int GetRange_UsedRangeColumnsCount()
  2702. {
  2703. if (m_objApp == null) { return 0; }
  2704. if (m_objSheet == null) { return 0; }
  2705. this.SetApp_Exit_EditMode();
  2706. try
  2707. {
  2708. object m_objUsedRange = m_objSheet.GetType().InvokeMember("UsedRange", BindingFlags.GetProperty, null, m_objSheet, null);
  2709. if (m_objUsedRange == null)
  2710. {
  2711. Console.WriteLine("出错啦: UsedRange == null。");
  2712. }
  2713. object m_objUsedRangeColumns = m_objUsedRange.GetType().InvokeMember("Columns", BindingFlags.GetProperty, null, m_objUsedRange, null);
  2714. int UsedRangeColumnsCount = (int)m_objUsedRangeColumns.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, m_objUsedRangeColumns, null);
  2715. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objUsedRangeColumns); //一定要注释,否则出错
  2716. GC.GetTotalMemory(true);
  2717. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objUsedRange);
  2718. GC.GetTotalMemory(true);
  2719. return UsedRangeColumnsCount;
  2720. }
  2721. catch (Exception ex)
  2722. {
  2723. MessageBox.Show("读取GetRange_UsedRangeColumnsCount错误!错误原因:" + ex.Message);
  2724. return 0;
  2725. }
  2726. }
  2727. /// <summary>
  2728. /// 得到已经使用的区域
  2729. /// </summary>
  2730. /// <returns></returns>
  2731. public string GetRange_UsedRange()
  2732. {
  2733. //System.Collections.ArrayList alUsedRange = new System.Collections.ArrayList();
  2734. string strUsedRange;
  2735. try
  2736. {
  2737. int nUsedRangeColumnsCount = this.GetRange_UsedRangeColumnsCount();
  2738. int nUsedRangeRowsCount = this.GetRange_UsedRangeRowsCount();
  2739. strUsedRange = SuperTools.UC_EmbedExcelIntoWinFormNoDLL.Tool_NtoL(nUsedRangeColumnsCount) + nUsedRangeRowsCount.ToString();
  2740. return strUsedRange;
  2741. }
  2742. catch (Exception ex)
  2743. {
  2744. MessageBox.Show("读取GetRange_UsedRange错误!错误原因:" + ex.Message);
  2745. return null;
  2746. }
  2747. }
  2748. /// <summary>
  2749. /// 设置整个使用区域,全部自动最适应列框
  2750. /// </summary>
  2751. /// <returns></returns>
  2752. public void SetRange_UsedRange_AutoFit()
  2753. {
  2754. string ss = this.GetRange_UsedRange();
  2755. this.SetRangeArray_RangeProperty_Columns_AutoFit("A1", ss);
  2756. this.SetRangeArray_RangeProperty_Rows_AutoFit("A1", ss);
  2757. }
  2758. /// <summary>
  2759. /// 设置单元格的格式 ,如:"#,##0.00_" = 数字格式
  2760. /// </summary>
  2761. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2762. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2763. /// <param name="_strFormatStyle"></param>
  2764. /// <returns></returns>
  2765. public bool SetRangeArray_FormatStyle(string _BeginPoint, string _EndPoint, string _strFormatStyle)
  2766. {
  2767. if (m_objApp == null) { return false; }
  2768. if (m_objSheet == null) { return false; }
  2769. this.SetApp_Exit_EditMode();
  2770. try
  2771. {
  2772. //得到range数组
  2773. //object[] Parameters_rangeArray = new object[] { "C1", "C5" };
  2774. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  2775. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  2776. if (m_objRangeArray == null)
  2777. {
  2778. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  2779. }
  2780. //得到写入值
  2781. Object[] ParametersArray_WriteValue = new Object[1];
  2782. ParametersArray_WriteValue[0] = _strFormatStyle; //赋值
  2783. //******************
  2784. m_objRangeArray.GetType().InvokeMember("NumberFormat", BindingFlags.SetProperty, null, m_objRangeArray, ParametersArray_WriteValue);
  2785. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  2786. GC.GetTotalMemory(true);
  2787. return true;
  2788. }
  2789. catch (Exception ex)
  2790. {
  2791. MessageBox.Show("设置数字格式错误!错误原因:" + ex.Message);
  2792. return false;
  2793. }
  2794. //G/通用格式
  2795. //"#,##0.00_ "
  2796. }
  2797. /// <summary>
  2798. /// 获取单元格的格式
  2799. /// </summary>
  2800. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  2801. /// <param name="_EndPoint">终止位置 如"B5"</param>
  2802. /// <returns></returns>
  2803. public string GetRangeArray_FormatStyle(string _BeginPoint, string _EndPoint)
  2804. {
  2805. if (m_objApp == null) { return String.Empty; }
  2806. if (m_objSheet == null) { return String.Empty; }
  2807. this.SetApp_Exit_EditMode();
  2808. try
  2809. {
  2810. //得到range数组
  2811. //object[] Parameters_rangeArray = new object[] { "C1", "C5" };
  2812. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  2813. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  2814. if (m_objRangeArray == null)
  2815. {
  2816. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  2817. }
  2818. //NumberFormatLocal //NumberFormat
  2819. string strColumn_NumberFormatLocal = (string)m_objRangeArray.GetType().InvokeMember("NumberFormat", BindingFlags.GetProperty, null, m_objRangeArray, null);
  2820. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  2821. GC.GetTotalMemory(true);
  2822. return strColumn_NumberFormatLocal; //
  2823. }
  2824. catch (Exception ex)
  2825. {
  2826. MessageBox.Show("获取单元格的格式GetRangeArray_FormatStyle错误!错误原因:" + ex.Message);
  2827. return null;
  2828. }
  2829. //G/通用格式
  2830. //"#,##0.00_ "
  2831. }
  2832. #region 学习用
  2833. /*
  2834. //根据DataTable的字段的数据类型来设置excel列的数据格式
  2835. DataTable table = new DataTable();
  2836. int i = 0;
  2837. foreach (DataColumn column in table.Columns)
  2838. {
  2839. i++;
  2840. // Insert fieldname
  2841. object range = m_objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, m_objSheet, new object[2] { 1, i });
  2842. if (range == null)
  2843. {
  2844. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  2845. }
  2846. range.GetType().InvokeMember("Value", BindingFlags.SetProperty | BindingFlags.OptionalParamBinding, null, range, new object[1] { column.ColumnName });
  2847. object[] format = null;
  2848. if (column.DataType.Equals(typeof(double)))
  2849. {
  2850. string s = "0" +
  2851. System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
  2852. for (int digits = 0; digits < System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalDigits; digits++)
  2853. {
  2854. s += "0";
  2855. }
  2856. format = new object[] { s.ToString() };
  2857. }
  2858. else if (column.DataType.Equals(typeof(int)))
  2859. {
  2860. format = new object[] { "0" };
  2861. }
  2862. else if (column.DataType.Equals(typeof(Int16)))
  2863. {
  2864. format = new object[] { "0" };
  2865. }
  2866. else if (column.DataType.Equals(typeof(DateTime)))
  2867. {
  2868. format = new object[] { "TT.MM.JJJJ HH:mm:ss" };
  2869. }
  2870. else if (column.DataType.Equals(typeof(string)))
  2871. {
  2872. format = new object[] { "" };
  2873. }
  2874. //Excel.Range oRange = (Excel.Range)ws.Columns[SpaltenNummer, Type.Missing];
  2875. range = m_objSheet.GetType().InvokeMember("Columns", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, m_objSheet, new object[2] { i, Type.Missing });
  2876. //range = sheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, sheet, new object[2] { 2, i });
  2877. //range.GetType().InvokeMember("EntireColumn", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, range, new object[0]).GetType().InvokeMember("NumberFormat", BindingFlags.SetProperty | BindingFlags.OptionalParamBinding, null, range, format);
  2878. range.GetType().InvokeMember("NumberFormat", BindingFlags.SetProperty | BindingFlags.OptionalParamBinding, null, range, format);
  2879. }
  2880. */
  2881. #endregion
  2882. #region 字母转换为数字 数字转换为字母
  2883. ///<summary>
  2884. /// 字母转换为数字,Excel列头,如A-1;AA-27
  2885. /// </summary>
  2886. /// <param name="strLetter">字母</param>
  2887. /// <returns>字母对应的数字</returns>
  2888. public static int Tool_LtoN(string strLetter)
  2889. {
  2890. int intRtn = 0;
  2891. string strLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  2892. if (strLetter.Length == 2)
  2893. intRtn += (strLetters.IndexOf(strLetter.Substring(0, 1)) + 1) * 26;
  2894. intRtn += strLetters.IndexOf(strLetter.Substring(strLetter.Length - 1, 1)) + 1;
  2895. return intRtn;
  2896. }
  2897. /// <summary>
  2898. /// 数字转换为字母,Excel列头,如1-A;27-AA
  2899. /// </summary>
  2900. /// <param name="intNumber">数字</param>
  2901. /// <returns>数字对应的字母</returns>
  2902. public static string Tool_NtoL(int intNumber)
  2903. {
  2904. if (intNumber > 702)
  2905. return String.Empty;
  2906. if (intNumber == 702)
  2907. return "ZZ";
  2908. string strRtn = String.Empty;
  2909. string strLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  2910. if (intNumber == 26)
  2911. {
  2912. strRtn = "Z";
  2913. }
  2914. else
  2915. {
  2916. if (intNumber > 26)
  2917. strRtn = strLetters.Substring(intNumber / 26 - 1, 1);
  2918. strRtn += strLetters.Substring((intNumber % 26) - 1, 1);
  2919. }
  2920. return strRtn;
  2921. }
  2922. #endregion 辅助函数
  2923. #region 从excel文件得到GetDataTable
  2924. /// <summary>
  2925. /// 读取excel打开的文件,如xls、xml、csv等文件的内容,写入到DataTable中
  2926. /// </summary>
  2927. /// <returns></returns>
  2928. public DataTable Tools_GetDataTableFromExcelSheet()
  2929. {
  2930. object[] m_Parameters;
  2931. System.Data.DataTable _Table = new System.Data.DataTable();
  2932. #region 读取第一行内容作为写入字段名
  2933. //********************************************************************************
  2934. System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
  2935. int ColumnNumber = 1;
  2936. while (true) //读取第一行内容作为写入字段名
  2937. {
  2938. m_Parameters = new object[2] { 1, ColumnNumber }; ; //第一行是字段名
  2939. object m_objCells = m_objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, m_objSheet, m_Parameters);
  2940. object m_objCellsValue = m_objCells.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, m_objCells, new object[0]);
  2941. if (m_objCellsValue == null) //有空则退出,不再继续管后面的列
  2942. {
  2943. break;
  2944. }
  2945. else
  2946. {
  2947. ColumnNumber++;
  2948. string strTemp = m_objCellsValue.ToString();
  2949. ParaColumns.Add(strTemp + "|String"); //System.String
  2950. }
  2951. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objCells);
  2952. GC.GetTotalMemory(true);
  2953. }
  2954. SuperTools.DataTableTools.Add_Columns(ref _Table, ParaColumns); //增加列
  2955. //********************************************************************************
  2956. #endregion
  2957. #region 读取excel的数据项
  2958. //********************************************************************************
  2959. int RowNumber = 1; //增加行
  2960. while (true) //读取除第一行以外的内容
  2961. {
  2962. object[] ColumnValue = new object[_Table.Columns.Count]; //定义该行的各列
  2963. for (int j = 0; j < _Table.Columns.Count; j++)
  2964. {
  2965. m_Parameters = new object[2] { RowNumber + 1, j + 1 }; //第i行,第j列
  2966. object m_objCells = m_objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, m_objSheet, m_Parameters);
  2967. object m_objCellsValue = m_objCells.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, m_objCells, new object[0]); //读值
  2968. //m_objCells.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, m_objCells, Parameters); //写值
  2969. //if (m_objCellsValue == null || m_objCellsValue.ToString().Trim() == String.Empty)
  2970. if (m_objCellsValue != null)
  2971. {
  2972. ColumnValue[j] = m_objCellsValue.ToString();
  2973. }
  2974. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objCells);
  2975. GC.GetTotalMemory(true);
  2976. }
  2977. if (ColumnValue[0] == null) //第1列的该行为,空,则不再增加新行
  2978. {
  2979. break;
  2980. }
  2981. else
  2982. {
  2983. _Table.Rows.Add(ColumnValue);  //增加该行
  2984. RowNumber++; //下一行
  2985. }
  2986. }
  2987. //********************************************************************************
  2988. #endregion
  2989. return _Table;
  2990. }
  2991. #endregion
  2992. #endregion
  2993. #region 保存、退出
  2994. /// <summary>
  2995. /// excel保存的文件格式
  2996. /// </summary>
  2997. public enum XlFileFormat
  2998. {
  2999. #region 枚举excel文件的格式
  3000. /// <summary>
  3001. ///
  3002. /// </summary>
  3003. xlCurrentPlatformText = -4158,
  3004. /// <summary>
  3005. ///
  3006. /// </summary>
  3007. xlWorkbookNormal = -4143,
  3008. /// <summary>
  3009. ///
  3010. /// </summary>
  3011. xlSYLK = 2,
  3012. /// <summary>
  3013. ///
  3014. /// </summary>
  3015. xlWKS = 4,
  3016. /// <summary>
  3017. ///
  3018. /// </summary>
  3019. xlWK1 = 5,
  3020. /// <summary>
  3021. ///
  3022. /// </summary>
  3023. xlCSV = 6,
  3024. /// <summary>
  3025. ///
  3026. /// </summary>
  3027. xlDBF2 = 7,
  3028. /// <summary>
  3029. ///
  3030. /// </summary>
  3031. xlDBF3 = 8,
  3032. /// <summary>
  3033. ///
  3034. /// </summary>
  3035. xlDIF = 9,
  3036. /// <summary>
  3037. ///
  3038. /// </summary>
  3039. xlDBF4 = 11,
  3040. /// <summary>
  3041. ///
  3042. /// </summary>
  3043. xlWJ2WD1 = 14,
  3044. /// <summary>
  3045. ///
  3046. /// </summary>
  3047. xlWK3 = 15,
  3048. /// <summary>
  3049. ///
  3050. /// </summary>
  3051. xlExcel2 = 16,
  3052. /// <summary>
  3053. ///
  3054. /// </summary>
  3055. xlTemplate = 17,
  3056. /// <summary>
  3057. ///
  3058. /// </summary>
  3059. xlAddIn = 18,
  3060. /// <summary>
  3061. ///
  3062. /// </summary>
  3063. xlTextMac = 19,
  3064. /// <summary>
  3065. ///
  3066. /// </summary>
  3067. xlTextWindows = 20,
  3068. /// <summary>
  3069. ///
  3070. /// </summary>
  3071. xlTextMSDOS = 21,
  3072. /// <summary>
  3073. ///
  3074. /// </summary>
  3075. xlCSVMac = 22,
  3076. /// <summary>
  3077. ///
  3078. /// </summary>
  3079. xlCSVWindows = 23,
  3080. /// <summary>
  3081. ///
  3082. /// </summary>
  3083. xlCSVMSDOS = 24,
  3084. /// <summary>
  3085. ///
  3086. /// </summary>
  3087. xlIntlMacro = 25,
  3088. /// <summary>
  3089. ///
  3090. /// </summary>
  3091. xlIntlAddIn = 26,
  3092. /// <summary>
  3093. ///
  3094. /// </summary>
  3095. xlExcel2FarEast = 27,
  3096. /// <summary>
  3097. ///
  3098. /// </summary>
  3099. xlWorks2FarEast = 28,
  3100. /// <summary>
  3101. ///
  3102. /// </summary>
  3103. xlExcel3 = 29,
  3104. /// <summary>
  3105. ///
  3106. /// </summary>
  3107. xlWK1FMT = 30,
  3108. /// <summary>
  3109. ///
  3110. /// </summary>
  3111. xlWK1ALL = 31,
  3112. /// <summary>
  3113. ///
  3114. /// </summary>
  3115. xlWK3FM3 = 32,
  3116. /// <summary>
  3117. ///
  3118. /// </summary>
  3119. xlExcel4 = 33,
  3120. /// <summary>
  3121. ///
  3122. /// </summary>
  3123. xlWQ1 = 34,
  3124. /// <summary>
  3125. ///
  3126. /// </summary>
  3127. xlExcel4Workbook = 35,
  3128. /// <summary>
  3129. ///
  3130. /// </summary>
  3131. xlTextPrinter = 36,
  3132. /// <summary>
  3133. ///
  3134. /// </summary>
  3135. xlWK4 = 38,
  3136. /// <summary>
  3137. ///
  3138. /// </summary>
  3139. xlExcel7 = 39,
  3140. /// <summary>
  3141. ///
  3142. /// </summary>
  3143. xlExcel5 = 39,
  3144. /// <summary>
  3145. ///
  3146. /// </summary>
  3147. xlWJ3 = 40,
  3148. /// <summary>
  3149. ///
  3150. /// </summary>
  3151. xlWJ3FJ3 = 41,
  3152. /// <summary>
  3153. ///
  3154. /// </summary>
  3155. xlUnicodeText = 42,
  3156. /// <summary>
  3157. ///
  3158. /// </summary>
  3159. xlExcel9795 = 43,
  3160. /// <summary>
  3161. ///
  3162. /// </summary>
  3163. xlHtml = 44,
  3164. /// <summary>
  3165. ///
  3166. /// </summary>
  3167. xlWebArchive = 45,
  3168. /// <summary>
  3169. ///
  3170. /// </summary>
  3171. xlXMLSpreadsheet = 46,
  3172. #endregion
  3173. }
  3174. /// <summary>
  3175. /// 文件保存
  3176. /// </summary>
  3177. /// <returns></returns>
  3178. public bool AppExcel_Save()
  3179. {
  3180. if (m_objApp == null) { return false; }
  3181. if (m_objBook == null) { return false; }
  3182. SetApp_Exit_EditMode(); //退出编辑模式
  3183. try
  3184. {
  3185. //m_objApp.GetType().InvokeMember("Save", BindingFlags.InvokeMethod, null, m_objApp, null); //ok
  3186. m_objBook.GetType().InvokeMember("Save", BindingFlags.InvokeMethod, null, m_objBook, null); //ok
  3187. //m_objSheet.GetType().InvokeMember("Save", BindingFlags.InvokeMethod, null, m_objSheet, null);//不能通过,必须SaveAs
  3188. return true;
  3189. }
  3190. catch (Exception ex)
  3191. {
  3192. string strErr = "Excel.Application保存时出错!出错原因:" + ex.Message;
  3193. System.Windows.Forms.MessageBox.Show(strErr);
  3194. return true;
  3195. }
  3196. }
  3197. /// <summary>
  3198. /// Excel保存
  3199. /// </summary>
  3200. /// <param name="m_strFileName">m_strFileName可以选择= null 或者 = "" </param>
  3201. public bool AppExcel_SaveAs(string m_strFileName)
  3202. {
  3203. if (m_objApp == null) { return false; }
  3204. if (m_objBook == null) { return false; }
  3205. SetApp_Exit_EditMode(); //退出编辑模式
  3206. try
  3207. {
  3208. //不提示保存
  3209. try
  3210. {
  3211. object[] m_Parameters_DisplayAlerts = new Object[1] { false };
  3212. m_objApp.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, m_objApp, m_Parameters_DisplayAlerts);
  3213. }
  3214. catch { }
  3215. if (m_strFileName == null || m_strFileName == "")
  3216. {
  3217. //不改名保存
  3218. m_objBook.GetType().InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, m_objBook, null);
  3219. }
  3220. else
  3221. {
  3222. //另存为
  3223. #region 另存为参数
  3224. object o_Filename = m_strFileName; // "123";
  3225. object o_FileFormat = System.Reflection.Missing.Value; // 缺省值
  3226. //object o_FileFormat = 1; //正常的excel的工作簿(bin文件)
  3227. //object o_FileFormat = XlFileFormat.xlXMLSpreadsheet ;
  3228. object o_Password = System.Reflection.Missing.Value;
  3229. object o_WriteResPassword = System.Reflection.Missing.Value;
  3230. object o_ReadOnlyRecommended = System.Reflection.Missing.Value;
  3231. object o_CreateBackup = System.Reflection.Missing.Value;
  3232. object o_Excel_XlSaveAsAccessMode_AccessMode = System.Reflection.Missing.Value;
  3233. object o_ConflictResolution = System.Reflection.Missing.Value;
  3234. object o_AddToMru = System.Reflection.Missing.Value;
  3235. object o_TextCodepage = System.Reflection.Missing.Value;
  3236. object o_TextVisualLayout = System.Reflection.Missing.Value;
  3237. object o_Local = System.Reflection.Missing.Value;
  3238. if (m_strFileName.Length > 4 && m_strFileName.Substring(m_strFileName.Length - 4, 4).ToLower() == ".xls")
  3239. {
  3240. o_FileFormat = 1; //正常的excel的工作簿(bin文件) ok
  3241. o_FileFormat = XlFileFormat.xlWorkbookNormal;
  3242. }
  3243. if (m_strFileName.Length > 4 && m_strFileName.Substring(m_strFileName.Length - 4, 4).ToLower() == ".csv")
  3244. {
  3245. o_FileFormat = XlFileFormat.xlCSV;
  3246. }
  3247. if (m_strFileName.Length > 4 && m_strFileName.Substring(m_strFileName.Length - 4, 4).ToLower() == ".xml")
  3248. {
  3249. o_FileFormat = XlFileFormat.xlXMLSpreadsheet;
  3250. }
  3251. object[] m_Parameters_objBookSaveAs = new Object[12];
  3252. m_Parameters_objBookSaveAs[0] = o_Filename;
  3253. m_Parameters_objBookSaveAs[1] = o_FileFormat;
  3254. m_Parameters_objBookSaveAs[2] = o_Password;
  3255. m_Parameters_objBookSaveAs[3] = o_WriteResPassword;
  3256. m_Parameters_objBookSaveAs[4] = o_ReadOnlyRecommended;
  3257. m_Parameters_objBookSaveAs[5] = o_CreateBackup;
  3258. m_Parameters_objBookSaveAs[6] = o_Excel_XlSaveAsAccessMode_AccessMode;
  3259. m_Parameters_objBookSaveAs[7] = o_ConflictResolution;
  3260. m_Parameters_objBookSaveAs[8] = o_AddToMru;
  3261. m_Parameters_objBookSaveAs[9] = o_TextCodepage;
  3262. m_Parameters_objBookSaveAs[10] = o_TextVisualLayout;
  3263. m_Parameters_objBookSaveAs[11] = o_Local;
  3264. #endregion
  3265. m_objBook.GetType().InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, m_objBook, m_Parameters_objBookSaveAs);
  3266. }
  3267. return true;
  3268. ////退出
  3269. //m_objApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, m_objApp, null);
  3270. }
  3271. catch (Exception ex)
  3272. {
  3273. string strErr = "Excel.Application保存时出错!出错原因:" + ex.Message;
  3274. System.Windows.Forms.MessageBox.Show(strErr);
  3275. return true;
  3276. }
  3277. }
  3278. /// <summary>
  3279. /// Excel退出
  3280. /// </summary>
  3281. /// <returns></returns>
  3282. public void AppExcel_Exit() //退出时报错
  3283. {
  3284. //if (m_objApp == null) { return false; }
  3285. //if (m_objBook == null) { return false; }
  3286. #region 退出 注销
  3287. try
  3288. {
  3289. //不提示保存
  3290. object[] m_Parameters_DisplayAlerts = new Object[1] { false };
  3291. m_objApp.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, m_objApp, m_Parameters_DisplayAlerts);
  3292. }
  3293. catch { };
  3294. //********************************************************************************
  3295. try
  3296. {
  3297. #region 关闭参数
  3298. object o_save_changes = false;
  3299. object o_Filename = System.Reflection.Missing.Value;
  3300. object o_route_workbook = System.Reflection.Missing.Value;
  3301. #endregion
  3302. object[] m_Parameters_objBookClose = new Object[3];
  3303. m_Parameters_objBookClose[0] = o_save_changes;
  3304. m_Parameters_objBookClose[1] = o_Filename;
  3305. m_Parameters_objBookClose[2] = o_route_workbook;
  3306. //退出Book
  3307. m_objBook.GetType().InvokeMember("Close", BindingFlags.InvokeMethod, null, m_objBook, m_Parameters_objBookClose);
  3308. //m_objBook.GetType().InvokeMember("Close", BindingFlags.InvokeMethod, null, m_objBook, null); //ok
  3309. //退出Books
  3310. m_objBooks.GetType().InvokeMember("Close", BindingFlags.InvokeMethod, null, m_objBooks, null);
  3311. m_objApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, m_objApp, null);
  3312. //return true;
  3313. }
  3314. catch (Exception ex)
  3315. {
  3316. string strErr = "Excel.Application退出时出错!出错原因:" + ex.Message;
  3317. //System.Windows.Forms.MessageBox.Show(strErr);
  3318. //return false;
  3319. }
  3320. finally
  3321. {
  3322. //System.Runtime.InteropServices.Marshal.ReleaseComObject(objCells);
  3323. if (m_objSheet != null)
  3324. {
  3325. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet);
  3326. GC.GetTotalMemory(true);
  3327. }
  3328. if (m_objSheets != null)
  3329. {
  3330. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheets);
  3331. GC.GetTotalMemory(true);
  3332. }
  3333. if (m_objBook != null)
  3334. {
  3335. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBook);
  3336. GC.GetTotalMemory(true);
  3337. }
  3338. if (m_objBooks != null)
  3339. {
  3340. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBooks);
  3341. GC.GetTotalMemory(true);
  3342. }
  3343. if (m_objApp != null)
  3344. {
  3345. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objApp);
  3346. GC.GetTotalMemory(true);
  3347. }
  3348. GC.Collect(); //强制对所有代进行垃圾回收
  3349. }
  3350. #endregion
  3351. //如果再有错误,弹出“Microsoft Office Excel 遇到问题需要关闭。我们对此引起的不便表示抱歉” ,则杀死该进程
  3352. try
  3353. {
  3354. this.Tools_KillExceProcess(this.LateBindingExcelStartTime, this.LateBindingExcelEndTime);
  3355. }
  3356. catch (Exception ex)
  3357. {
  3358. MessageBox.Show("杀死进程错误:" + ex.Message);
  3359. }
  3360. }
  3361. #endregion
  3362. /// <summary>
  3363. /// 杀死Excel.exe的进程
  3364. /// </summary>
  3365. /// <param name="beforeTime">Excel.exe进程的启动时间</param>
  3366. /// <param name="afterTime">Excel.exe进程启动完毕后的时间</param>
  3367. public void Tools_KillExceProcess(DateTime beforeTime, DateTime afterTime)
  3368. {
  3369. System.Diagnostics.Process[] myProcesses;
  3370. DateTime startTime;
  3371. myProcesses = System.Diagnostics.Process.GetProcessesByName("Excel");
  3372. //得不到Excel进程ID,暂时只能判断进程启动时间
  3373. foreach (System.Diagnostics.Process myProcess in myProcesses)
  3374. {
  3375. startTime = myProcess.StartTime;
  3376. if (startTime >= beforeTime && startTime <= afterTime)
  3377. {
  3378. myProcess.Kill();
  3379. }
  3380. }
  3381. }
  3382. #endregion
  3383. #region 窗体嵌入到父窗体,并重画
  3384. /// <summary>
  3385. /// 子窗体嵌入到父窗体
  3386. /// </summary>
  3387. private void EmbedIntoWindows()
  3388. {
  3389. #region 删除式样文件
  3390. //Environment.UserName
  3391. //System.Environment.UserDomainName
  3392. //WindowsIdentity.GetCurrent(false).Name;
  3393. //C:\Documents and Settings\Administrator\Application Data\Microsoft\Excel\Excel11.xlb
  3394. string LoginName = System.Environment.UserName; //计算机名字
  3395. string strExcelStyleFileName = "C:\\Documents and Settings\\" + LoginName + "\\Application Data\\Microsoft\\Excel\\Excel11.xlb";
  3396. if (System.IO.File.Exists(strExcelStyleFileName) == true)
  3397. {
  3398. System.IO.File.Delete(strExcelStyleFileName);
  3399. }
  3400. #endregion
  3401. #region
  3402. if (this.appSubWinHandle == IntPtr.Zero)
  3403. {
  3404. MessageBox.Show("没有指定子窗体的句柄:appSubWinHandle");
  3405. }
  3406. #endregion
  3407. myWin32API.SetParent(this.appSubWinHandle, this.Handle);   //子窗体嵌入到父窗体
  3408. //****************************************************************************
  3409. //设置显示式样
  3410. //myWin32API.SetWindowLong(this.appSubWinHandle, myWin32API.GWL_STYLE, new IntPtr(myWin32API.WS_VISIBLE)); //全部显示okokok
  3411. //****************************************************************************
  3412. int nNewStyle = myWin32API.GetWindowLong(this.appSubWinHandle, myWin32API.GWL_STYLE);
  3413. //nNewStyle &= ~myWin32API.WS_SYSMENU; //去掉将window的关闭按钮和最大最小化按钮,但是需要显示title
  3414. //nNewStyle &= ~myWin32API.WS_EX_TOOLWINDOW; //去掉将window的关闭按钮,但是需要显示title和最大最小化按钮
  3415. nNewStyle &= ~myWin32API.WS_DLGFRAME; //去掉Micrisoft标题栏title
  3416. //nNewStyle &= ~myWin32API.WS_BORDER; //
  3417. //**************************************************
  3418. //**************************************************
  3419. /*
  3420. //**************************************************
  3421. int hMenu = myWin32API.GetSystemMenu((Int32)this.appSubWinHandle, false);
  3422. int menuItemCount = myWin32API.GetMenuItemCount(hMenu);
  3423. if (hMenu > 0)
  3424. {
  3425. for (int i = 0; i <= menuItemCount + 1; i++)
  3426. {
  3427. int y = myWin32API.GetMenuItemID(hMenu, i);
  3428. int x = myWin32API.RemoveMenu(hMenu, i, myWin32API.MF_REMOVE);
  3429. }
  3430. }
  3431. myWin32API.DrawMenuBar((Int32)this.appSubWinHandle);
  3432. //**********************************************************************************************************
  3433. IntPtr hSysMenu = myWin32API.GetSystemMenu(this.appSubWinHandle, 0);
  3434. int xxx= myWin32API.DeleteMenu(hSysMenu, 0xF060, myWin32API.MF_BYCOMMAND);
  3435. if (hMenu > 0)
  3436. {
  3437. for (int i = 0; i <= menuItemCount + 1; i++)
  3438. {
  3439. int xx = myWin32API.DeleteMenu(hSysMenu, 0xF060, myWin32API.MF_BYCOMMAND);
  3440. //int x = myWin32API.DeleteMenu((IntPtr)hMenu, i, myWin32API.MF_BYPOSITION | myWin32API.MF_BYCOMMAND);
  3441. }
  3442. }
  3443. myWin32API.DrawMenuBar((Int32)this.appSubWinHandle);
  3444. //**********************************************************************************************************
  3445. try
  3446. {
  3447. //if (hMenu > 0)
  3448. //{
  3449. // int menuItemCount =myWin32API. GetMenuItemCount(hMenu);
  3450. // myWin32API.RemoveMenu(hMenu, menuItemCount - 1, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
  3451. // myWin32API.RemoveMenu(hMenu, menuItemCount - 2, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
  3452. // myWin32API.RemoveMenu(hMenu, menuItemCount - 3, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
  3453. // myWin32API.RemoveMenu(hMenu, menuItemCount - 4, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
  3454. // myWin32API.RemoveMenu(hMenu, menuItemCount - 5, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
  3455. // myWin32API.RemoveMenu(hMenu, menuItemCount - 6, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
  3456. // myWin32API.RemoveMenu(hMenu, menuItemCount - 7, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
  3457. // //myWin32API.RemoveMenu(hMenu, menuItemCount - 8, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
  3458. // myWin32API.DrawMenuBar((Int32)this.appSubWinHandle);
  3459. //}
  3460. }
  3461. catch (Exception ex)
  3462. {
  3463. System.Windows.Forms.MessageBox.Show("移除系统菜单出错" + ex.Message);
  3464. }
  3465. */
  3466. //**************************************************
  3467. //**************************************************
  3468. //***********************
  3469. myWin32API.SetWindowLong(this.appSubWinHandle, myWin32API.GWL_STYLE, nNewStyle); //设置窗口新式样
  3470. ReDraw();
  3471. ReDraw();
  3472. //***********************
  3473. }
  3474. //重画
  3475. private void ReDraw()
  3476. {
  3477. if (this.appSubWinHandle != IntPtr.Zero)
  3478. {
  3479. //myWin32API.MoveWindow(this.appSubWinHandle, 0, 0, this.Width, this.Height, true);
  3480. //myWin32API.SetWindowPos2(this.appSubWinHandle.ToInt32(), this.Handle.ToInt32(),
  3481. // 0, 0,
  3482. // this.Bounds.Width + 20, this.Bounds.Height + 20,
  3483. // myWin32API.SWP_NOZORDER | myWin32API.SWP_NOMOVE | myWin32API.SWP_DRAWFRAME);
  3484. myWin32API.SetWindowPos(this.appSubWinHandle, this.Handle,
  3485. 0, 0,
  3486. this.Bounds.Width, this.Bounds.Height,
  3487. myWin32API.SWP_NOZORDER | myWin32API.SWP_NOMOVE | myWin32API.SWP_DRAWFRAME);
  3488. myWin32API.MoveWindow(this.appSubWinHandle, 0, 0, this.Width, this.Height, true);  // Move the window to overlay it on this window
  3489. }
  3490. if (this.Parent != null)
  3491. {
  3492. this.Parent.Focus();
  3493. }
  3494. }
  3495. #endregion
  3496. }
  3497. #endregion
  3498. #region (静态类) 调用 API函数
  3499. /// <summary>
  3500. /// 调用 API函数
  3501. /// </summary>
  3502. public class myWin32API
  3503. {
  3504. #region 得到当前窗体的句柄
  3505. //GetFocus()得到的肯定是ActiveWindow,但是GetActiveWindow()的窗口不一定是有输入焦点的窗口。
  3506. //GetForegroundWindow()是和窗口在Z-ORDER里的位置有关的。
  3507. //比如说一个ACTIVE WINDOW上面还有一个NOT ACTIVE WINDOW,但这个窗口的属性是TOPMOST。GetForegroundWindow()只能取得上面的这个窗口
  3508. /// <summary>
  3509. /// Win32: GetForegroundWindow()
  3510. /// </summary>
  3511. /// <returns></returns>
  3512. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
  3513. public static extern IntPtr GetForegroundWindow(); //获得当前活动窗口句柄
  3514. /// <summary>
  3515. /// Win32: GetFocus()
  3516. /// </summary>
  3517. /// <returns></returns>
  3518. [DllImport("user32.dll", CharSet = CharSet.Auto)]
  3519. public static extern IntPtr GetFocus();
  3520. /// <summary>
  3521. ///
  3522. /// </summary>
  3523. /// <param name="hwnd"></param>
  3524. /// <returns></returns>
  3525. [DllImport("user32.dll ")]
  3526. public static extern int SetFocus(IntPtr hwnd);
  3527. /// <summary>
  3528. ///
  3529. /// </summary>
  3530. /// <returns></returns>
  3531. [DllImport("User32.DLL")]
  3532. public static extern IntPtr GetActiveWindow();
  3533. #endregion
  3534. #region 模拟鼠标的移动、点击等动作
  3535. /// <summary>
  3536. /// 该函数可以改变鼠标指针的位置。其中X,Y是相对于屏幕左上角的绝对位置。
  3537. /// </summary>
  3538. /// <param name="X"></param>
  3539. /// <param name="Y"></param>
  3540. /// <returns></returns>
  3541. [DllImport("user32.dll")]
  3542. static extern bool SetCursorPos(int X, int Y);
  3543. /// <summary>
  3544. /// 可以设置鼠标指针绝对的位置,而且可以以相对坐标来设置。另外,该函数还可以模拟鼠标左右键点击、鼠标滚轮操作等。
  3545. /// </summary>
  3546. /// <param name="flags">一个基于uint类型的枚举,鼠标d的动作类型</param>
  3547. /// <param name="dx"></param>
  3548. /// <param name="dy"></param>
  3549. /// <param name="data"></param>
  3550. /// <param name="extraInfo"></param>
  3551. [DllImport("user32.dll")]
  3552. static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);
  3553. [Flags]
  3554. enum MouseEventFlag : uint
  3555. {
  3556. Move = 0x0001,
  3557. LeftDown = 0x0002,
  3558. LeftUp = 0x0004,
  3559. RightDown = 0x0008,
  3560. RightUp = 0x0010,
  3561. MiddleDown = 0x0020,
  3562. MiddleUp = 0x0040,
  3563. XDown = 0x0080,
  3564. XUp = 0x0100,
  3565. Wheel = 0x0800,
  3566. VirtualDesk = 0x4000,
  3567. Absolute = 0x8000
  3568. }
  3569. #endregion
  3570. #region 定义API方法
  3571. /// <summary>
  3572. ///
  3573. /// </summary>
  3574. /// <param name="hWnd"></param>
  3575. /// <param name="nCmdShow"></param>
  3576. /// <returns></returns>
  3577. [DllImport("user32.dll")]
  3578. public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
  3579. /// <summary>
  3580. ///
  3581. /// </summary>
  3582. /// <param name="hWnd"></param>
  3583. /// <returns></returns>
  3584. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
  3585. public static extern bool SetForegroundWindow(IntPtr hWnd);
  3586. /// <summary>
  3587. ///
  3588. /// </summary>
  3589. /// <param name="hWnd"></param>
  3590. /// <returns></returns>
  3591. [DllImport("user32.dll")]
  3592. public static extern bool IsIconic(IntPtr hWnd);
  3593. /// <summary>
  3594. ///
  3595. /// </summary>
  3596. /// <param name="hWnd"></param>
  3597. /// <returns></returns>
  3598. [DllImport("user32.dll")]
  3599. public static extern bool IsZoomed(IntPtr hWnd);
  3600. #region //********API32函数声明**************
  3601. // **********************************************************************
  3602. //// Win32: SetWindowsHookEx()
  3603. //[DllImport("user32.dll", CharSet = CharSet.Auto,
  3604. // CallingConvention = CallingConvention.StdCall)]
  3605. //private static extern IntPtr SetWindowsHookEx(HookType code,
  3606. // HookProc func,
  3607. // IntPtr hInstance,
  3608. // int threadID);
  3609. /// <summary>
  3610. /// Win32: UnhookWindowsHookEx()
  3611. /// </summary>
  3612. /// <param name="hhook"></param>
  3613. /// <returns></returns>
  3614. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
  3615. public static extern int UnhookWindowsHookEx(IntPtr hhook);
  3616. /// <summary>
  3617. /// Win32: CallNextHookEx()
  3618. /// </summary>
  3619. /// <param name="hhook"></param>
  3620. /// <param name="nCode"></param>
  3621. /// <param name="wParam"></param>
  3622. /// <param name="lParam"></param>
  3623. /// <returns></returns>
  3624. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
  3625. public static extern int CallNextHookEx(IntPtr hhook, int nCode, int wParam, IntPtr lParam);
  3626. /// <summary>
  3627. /// Win32: GetModuleHandle()
  3628. /// </summary>
  3629. /// <param name="lpModuleName"></param>
  3630. /// <returns></returns>
  3631. [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
  3632. private static extern IntPtr GetModuleHandle(string lpModuleName);
  3633. /// <summary>
  3634. ///
  3635. /// </summary>
  3636. /// <param name="hWnd"></param>
  3637. /// <param name="ProcessId"></param>
  3638. /// <returns></returns>
  3639. [DllImport("user32.dll")]
  3640. public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId); ////获得活动窗口的线程号
  3641. /// <summary>
  3642. /// Win32: GetWindowThreadProcessId()
  3643. /// </summary>
  3644. /// <param name="hwnd"></param>
  3645. /// <param name="lpdwProcessId"></param>
  3646. /// <returns></returns>
  3647. [DllImport("user32.dll", CharSet = CharSet.Auto)]
  3648. public static extern int GetWindowThreadProcessId(IntPtr hwnd, int lpdwProcessId); ////获得活动窗口的线程号
  3649. /// <summary>
  3650. /// Win32: GetCurrentThreadId
  3651. /// </summary>
  3652. /// <returns></returns>
  3653. [DllImport("kernel32.dll", EntryPoint = "GetCurrentThreadId")]
  3654. public static extern int GetCurrentThreadId();
  3655. /// <summary>
  3656. /// Win32: AttachThreadInput()
  3657. /// </summary>
  3658. /// <param name="idAttach"></param>
  3659. /// <param name="idAttachTo"></param>
  3660. /// <param name="fAttach"></param>
  3661. /// <returns></returns>
  3662. [DllImport("user32.dll", CharSet = CharSet.Auto)]
  3663. private static extern int AttachThreadInput(int idAttach, int idAttachTo, int fAttach);
  3664. /// <summary>
  3665. ///
  3666. /// </summary>
  3667. /// <param name="idAttach"></param>
  3668. /// <param name="idAttachTo"></param>
  3669. /// <param name="fAttach"></param>
  3670. /// <returns></returns>
  3671. [DllImport("user32.dll")]
  3672. public static extern IntPtr AttachThreadInput(IntPtr idAttach, IntPtr idAttachTo, int fAttach);
  3673. /// <summary>
  3674. /// Win32: SendMessage()
  3675. /// </summary>
  3676. /// <param name="hwnd"></param>
  3677. /// <param name="wMsg"></param>
  3678. /// <param name="wParam"></param>
  3679. /// <param name="lParam"></param>
  3680. /// <returns></returns>
  3681. [DllImport("user32.dll", CharSet = CharSet.Auto)]
  3682. private static extern int SendMessage(HandleRef hwnd, int wMsg, int wParam, int lParam);
  3683. /// <summary>
  3684. ///
  3685. /// </summary>
  3686. /// <param name="hwnd"></param>
  3687. /// <param name="wMsg"></param>
  3688. /// <param name="wParam"></param>
  3689. /// <param name="lParam"></param>
  3690. /// <returns></returns>
  3691. [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
  3692. public static extern int SendMessageString(HandleRef hwnd, int wMsg, int wParam, StringBuilder lParam);
  3693. /// <summary>
  3694. /// Win32: GetWindowText()
  3695. /// </summary>
  3696. /// <param name="hwnd"></param>
  3697. /// <param name="lpString"></param>
  3698. /// <param name="nMaxCount"></param>
  3699. /// <returns></returns>
  3700. [DllImport("user32.dll", CharSet = CharSet.Auto)]
  3701. private static extern int GetWindowText(IntPtr hwnd, StringBuilder lpString, int nMaxCount);
  3702. /// <summary>
  3703. /// Win32: GetClassName()
  3704. /// </summary>
  3705. /// <param name="hwnd"></param>
  3706. /// <param name="lpClassName"></param>
  3707. /// <param name="nMaxCount"></param>
  3708. /// <returns></returns>
  3709. [DllImport("user32.dll", CharSet = CharSet.Auto)]
  3710. private static extern int GetClassName(IntPtr hwnd, StringBuilder lpClassName, int nMaxCount);
  3711. #endregion
  3712. #region DDE学习用
  3713. //*************************
  3714. /// <summary>
  3715. ///
  3716. /// </summary>
  3717. /// <param name="hwnd"></param>
  3718. /// <param name="nIDEvent"></param>
  3719. /// <param name="uElapse"></param>
  3720. /// <param name="lpTimerFunc"></param>
  3721. /// <returns></returns>
  3722. [DllImport("user32.dll", SetLastError = true)]
  3723. public static extern long SetTimer(IntPtr hwnd, long nIDEvent, long uElapse, long lpTimerFunc);
  3724. /// <summary>
  3725. ///
  3726. /// </summary>
  3727. /// <param name="hwnd"></param>
  3728. /// <param name="nIDEvent"></param>
  3729. /// <returns></returns>
  3730. [DllImport("user32.dll", SetLastError = true)]
  3731. public static extern long KillTimer(IntPtr hwnd, long nIDEvent);
  3732. //************************
  3733. /// <summary>
  3734. ///
  3735. /// </summary>
  3736. /// <param name="idInst"></param>
  3737. /// <param name="hszService"></param>
  3738. /// <param name="hszTopic"></param>
  3739. /// <param name="pCC"></param>
  3740. /// <returns></returns>
  3741. [DllImport("user32.dll", EntryPoint = "DdeConnect", CharSet = CharSet.Ansi)]
  3742. public static extern IntPtr DdeConnect(uint idInst, IntPtr hszService, IntPtr hszTopic, IntPtr pCC);
  3743. /// <summary>
  3744. ///
  3745. /// </summary>
  3746. /// <param name="idInst"></param>
  3747. /// <param name="pSrc"></param>
  3748. /// <param name="cb"></param>
  3749. /// <param name="cbOff"></param>
  3750. /// <param name="hszItem"></param>
  3751. /// <param name="wFmt"></param>
  3752. /// <param name="afCmd"></param>
  3753. /// <returns></returns>
  3754. [DllImport("user32.dll", EntryPoint = "DdeCreateDataHandle", CharSet = CharSet.Ansi)]
  3755. public static extern IntPtr DdeCreateDataHandle(
  3756. uint idInst, byte[] pSrc, uint cb, uint cbOff, IntPtr hszItem, uint wFmt, uint afCmd);
  3757. /// <summary>
  3758. ///
  3759. /// </summary>
  3760. /// <param name="idInst"></param>
  3761. /// <param name="psz"></param>
  3762. /// <param name="iCodePage"></param>
  3763. /// <returns></returns>
  3764. [DllImport("user32.dll", EntryPoint = "DdeCreateStringHandle", CharSet = CharSet.Ansi)]
  3765. public static extern IntPtr DdeCreateStringHandle(uint idInst, string psz, int iCodePage);
  3766. /// <summary>
  3767. ///
  3768. /// </summary>
  3769. /// <param name="hConv"></param>
  3770. /// <returns></returns>
  3771. [DllImport("user32.dll", EntryPoint = "DdeDisconnect", CharSet = CharSet.Ansi)]
  3772. public static extern bool DdeDisconnect(IntPtr hConv);
  3773. /// <summary>
  3774. ///
  3775. /// </summary>
  3776. /// <param name="idInst"></param>
  3777. /// <param name="hConv"></param>
  3778. /// <param name="wCmd"></param>
  3779. /// <returns></returns>
  3780. [DllImport("user32.dll", EntryPoint = "DdeEnableCallback", CharSet = CharSet.Ansi)]
  3781. public static extern bool DdeEnableCallback(uint idInst, IntPtr hConv, uint wCmd);
  3782. /// <summary>
  3783. ///
  3784. /// </summary>
  3785. /// <param name="hData"></param>
  3786. /// <returns></returns>
  3787. [DllImport("user32.dll", EntryPoint = "DdeFreeDataHandle", CharSet = CharSet.Ansi)]
  3788. public static extern bool DdeFreeDataHandle(IntPtr hData);
  3789. /// <summary>
  3790. ///
  3791. /// </summary>
  3792. /// <param name="idInst"></param>
  3793. /// <param name="hsz"></param>
  3794. /// <returns></returns>
  3795. [DllImport("user32.dll", EntryPoint = "DdeFreeStringHandle", CharSet = CharSet.Ansi)]
  3796. public static extern bool DdeFreeStringHandle(uint idInst, IntPtr hsz);
  3797. /// <summary>
  3798. ///
  3799. /// </summary>
  3800. /// <param name="hData"></param>
  3801. /// <param name="pDst"></param>
  3802. /// <param name="cbMax"></param>
  3803. /// <param name="cbOff"></param>
  3804. /// <returns></returns>
  3805. [DllImport("user32.dll", EntryPoint = "DdeGetData", CharSet = CharSet.Ansi)]
  3806. public static extern uint DdeGetData(IntPtr hData, [Out] byte[] pDst, uint cbMax, uint cbOff);
  3807. //[DllImport("user32.dll", EntryPoint = "DdeInitialize", CharSet = CharSet.Ansi)]
  3808. //public static extern uint DdeInitialize(ref uint pidInst, DdeDelegate pfnCallback, uint afCmd, uint ulRes);
  3809. /// <summary>
  3810. ///
  3811. /// </summary>
  3812. /// <param name="idInst"></param>
  3813. /// <param name="hsz"></param>
  3814. /// <param name="psz"></param>
  3815. /// <param name="cchMax"></param>
  3816. /// <param name="iCodePage"></param>
  3817. /// <returns></returns>
  3818. [DllImport("user32.dll", EntryPoint = "DdeQueryString", CharSet = CharSet.Ansi)]
  3819. public static extern uint DdeQueryString(uint idInst, IntPtr hsz, StringBuilder psz, uint cchMax, int iCodePage);
  3820. /// <summary>
  3821. ///
  3822. /// </summary>
  3823. /// <param name="idInst"></param>
  3824. /// <returns></returns>
  3825. [DllImport("user32.dll", EntryPoint = "DdeUninitialize", CharSet = CharSet.Ansi)]
  3826. public static extern bool DdeUninitialize(uint idInst);
  3827. #endregion
  3828. /// <summary>
  3829. /// SetParent
  3830. /// </summary>
  3831. /// <param name="hWndChild"></param>
  3832. /// <param name="hWndNewParent"></param>
  3833. /// <returns></returns>
  3834. [DllImport("user32.dll", SetLastError = true)]
  3835. public static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
  3836. /// <summary>
  3837. /// MoveWindow
  3838. /// </summary>
  3839. /// <param name="hwnd"></param>
  3840. /// <param name="x"></param>
  3841. /// <param name="y"></param>
  3842. /// <param name="cx"></param>
  3843. /// <param name="cy"></param>
  3844. /// <param name="repaint"></param>
  3845. /// <returns></returns>
  3846. [DllImport("user32.dll", SetLastError = true)]
  3847. public static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);
  3848. //bool repaint是否接受原始窗体
  3849. /// <summary>
  3850. /// GetSystemMenu
  3851. /// </summary>
  3852. /// <param name="hWnd"></param>
  3853. /// <param name="Revert"></param>
  3854. /// <returns></returns>
  3855. [DllImport("user32.dll", EntryPoint = "GetSystemMenu")]
  3856. public static extern Int32 GetSystemMenu(Int32 hWnd, int Revert);
  3857. /// <summary>
  3858. /// GetSystemMenu
  3859. /// </summary>
  3860. /// <param name="hWnd"></param>
  3861. /// <param name="Revert"></param>
  3862. /// <returns></returns>
  3863. [DllImport("user32.dll", EntryPoint = "GetSystemMenu")] //第二种方法
  3864. public static extern Int32 GetSystemMenu(Int32 hWnd, bool Revert);
  3865. /// <summary>
  3866. /// GetSystemMenu
  3867. /// </summary>
  3868. /// <param name="hwnd"></param>
  3869. /// <param name="bRevert"></param>
  3870. /// <returns></returns>
  3871. [DllImport("user32.dll", EntryPoint = "GetSystemMenu")] //第三种方法
  3872. public static extern IntPtr GetSystemMenu(IntPtr hwnd, int bRevert);
  3873. /// <summary>
  3874. /// GetMenuItemCount
  3875. /// </summary>
  3876. /// <param name="hMenu"></param>
  3877. /// <returns></returns>
  3878. [DllImport("user32.dll", EntryPoint = "GetMenuItemCount")]
  3879. public static extern Int32 GetMenuItemCount(Int32 hMenu);
  3880. /// <summary>
  3881. /// GetMenuItemID
  3882. /// </summary>
  3883. /// <param name="Menuhandle"></param>
  3884. /// <param name="pos"></param>
  3885. /// <returns></returns>
  3886. [DllImport("user32.dll")]
  3887. public static extern int GetMenuItemID(int Menuhandle, int pos);
  3888. /// <summary>
  3889. /// RemoveMenu
  3890. /// </summary>
  3891. /// <param name="hMenu"></param>
  3892. /// <param name="nPosition"></param>
  3893. /// <param name="wFlags"></param>
  3894. /// <returns></returns>
  3895. [DllImport("user32.dll", EntryPoint = "RemoveMenu")]
  3896. public static extern Int32 RemoveMenu(Int32 hMenu, Int32 nPosition, Int32 wFlags);
  3897. /// <summary>
  3898. /// DeleteMenu
  3899. /// </summary>
  3900. /// <param name="hMenu"></param>
  3901. /// <param name="nPosition"></param>
  3902. /// <param name="wFlags"></param>
  3903. /// <returns></returns>
  3904. [DllImport("user32.dll", EntryPoint = "DeleteMenu")]
  3905. public static extern int DeleteMenu(
  3906. IntPtr hMenu,
  3907. int nPosition,
  3908. int wFlags);
  3909. /// <summary>
  3910. /// DrawMenuBar
  3911. /// </summary>
  3912. /// <param name="hWnd"></param>
  3913. /// <returns></returns>
  3914. [DllImport("user32.dll", EntryPoint = "DrawMenuBar")]
  3915. public static extern Int32 DrawMenuBar(Int32 hWnd);
  3916. /// <summary>
  3917. /// GetWindowThreadProcessId
  3918. /// </summary>
  3919. /// <param name="hWnd"></param>
  3920. /// <param name="lpdwProcessId"></param>
  3921. /// <returns></returns>
  3922. [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId", SetLastError = true,
  3923. CharSet = CharSet.Unicode, ExactSpelling = true,
  3924. CallingConvention = CallingConvention.StdCall)]
  3925. private static extern long GetWindowThreadProcessId(long hWnd, long lpdwProcessId);
  3926. /// <summary>
  3927. /// FindWindow
  3928. /// </summary>
  3929. /// <param name="lpClassName"></param>
  3930. /// <param name="lpWindowName"></param>
  3931. /// <returns></returns>
  3932. [DllImport("user32.dll", SetLastError = true)]
  3933. private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
  3934. /// <summary>
  3935. /// SetWindowLong
  3936. /// </summary>
  3937. /// <param name="hWnd"></param>
  3938. /// <param name="nIndex"></param>
  3939. /// <param name="dwNewLong"></param>
  3940. /// <returns></returns>
  3941. [DllImport("user32.dll", EntryPoint = "SetWindowLongA", SetLastError = true)]
  3942. public static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong); //第二种方法
  3943. /// <summary>
  3944. /// SetWindowPos
  3945. /// </summary>
  3946. /// <param name="hwnd"></param>
  3947. /// <param name="hWndInsertAfter"></param>
  3948. /// <param name="x"></param>
  3949. /// <param name="y"></param>
  3950. /// <param name="cx"></param>
  3951. /// <param name="cy"></param>
  3952. /// <param name="wFlags"></param>
  3953. /// <returns></returns>
  3954. [DllImport("user32.dll", SetLastError = true)]
  3955. public static extern long SetWindowPos(IntPtr hwnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint wFlags);
  3956. /// <summary>
  3957. /// SetWindowPos2
  3958. /// </summary>
  3959. /// <param name="hWnd"></param>
  3960. /// <param name="hWndInsertAfter"></param>
  3961. /// <param name="X"></param>
  3962. /// <param name="Y"></param>
  3963. /// <param name="cx"></param>
  3964. /// <param name="cy"></param>
  3965. /// <param name="uFlags"></param>
  3966. /// <returns></returns>
  3967. [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
  3968. public static extern bool SetWindowPos2(
  3969. int hWnd, // handle to window
  3970. int hWndInsertAfter, // placement-order handle
  3971. int X, // horizontal position
  3972. int Y, // vertical position
  3973. int cx, // width
  3974. int cy, // height
  3975. uint uFlags // window-positioning options
  3976. );
  3977. [DllImport("user32.dll", EntryPoint = "PostMessageA", SetLastError = true)]
  3978. private static extern bool PostMessage(IntPtr hwnd, uint Msg, long wParam, long lParam);
  3979. /// <summary>
  3980. /// SetWindowLong
  3981. /// </summary>
  3982. /// <param name="hWnd"></param>
  3983. /// <param name="nIndex"></param>
  3984. /// <param name="newN"></param>
  3985. /// <returns></returns>
  3986. [DllImport("user32.dll")]
  3987. public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int newN);
  3988. /// <summary>
  3989. /// GetWindowLong
  3990. /// </summary>
  3991. /// <param name="hWnd"></param>
  3992. /// <param name="nIndex"></param>
  3993. /// <returns></returns>
  3994. [DllImport("user32.dll")]
  3995. public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
  3996. #endregion
  3997. //******************************************************
  3998. #region 定义 常量
  3999. /// <summary>
  4000. ///
  4001. /// </summary>
  4002. public const int GWL_STYLE = -16; //设置新的窗口风格
  4003. /// <summary>
  4004. ///
  4005. /// </summary>
  4006. public const int GWL_EXSTYLE = -20;
  4007. /// <summary>
  4008. ///
  4009. /// </summary>
  4010. public const int WS_CAPTION = 0x00C00000; //WS_CAPTION = WS_BORDER | WS_DLGFRAME; //window with a title bar
  4011. /// <summary>
  4012. ///
  4013. /// </summary>
  4014. public const int WS_SYSMENU = 0x00080000;
  4015. /// <summary>
  4016. ///
  4017. /// </summary>
  4018. public const int MF_BYCOMMAND = 0x0;
  4019. /// <summary>
  4020. ///
  4021. /// </summary>
  4022. public const int WS_VISIBLE = 0x10000000;
  4023. /// <summary>
  4024. ///
  4025. /// </summary>
  4026. public const int HWND_NOTOPMOST = -2;
  4027. /// <summary>
  4028. ///
  4029. /// </summary>
  4030. public const int MF_BYPOSITION = 0x400;
  4031. /// <summary>
  4032. ///
  4033. /// </summary>
  4034. public const int MF_REMOVE = 0x1000;
  4035. /// <summary>
  4036. ///
  4037. /// </summary>
  4038. public const int WS_MAXIMIZEBOX = 0x00010000; //
  4039. /// <summary>
  4040. ///
  4041. /// </summary>
  4042. public const int WS_MINIMIZEBOX = 0x00020000; //
  4043. /// <summary>
  4044. ///
  4045. /// </summary>
  4046. public const int SWP_DRAWFRAME = 0x20;
  4047. /// <summary>
  4048. ///
  4049. /// </summary>
  4050. public const int SWP_NOOWNERZORDER = 0x200; // Dont do owner Z ordering
  4051. /// <summary>
  4052. ///
  4053. /// </summary>
  4054. public const int SWP_NOREDRAW = 0x8; //
  4055. /// <summary>
  4056. ///
  4057. /// </summary>
  4058. public const int SWP_NOZORDER = 0x4; //
  4059. /// <summary>
  4060. ///
  4061. /// </summary>
  4062. public const int SWP_SHOWWINDOW = 0x0040;
  4063. /// <summary>
  4064. ///
  4065. /// </summary>
  4066. public const int SWP_HIDEWINDOW = 0x0080;
  4067. /// <summary>
  4068. ///
  4069. /// </summary>
  4070. public const int SWP_FRAMECHANGED = 0x20; //H20 The frame changed: send WM_NCCALCSIZE
  4071. /// <summary>
  4072. ///
  4073. /// </summary>
  4074. public const int SWP_NOACTIVATE = 0x10;
  4075. /// <summary>
  4076. ///
  4077. /// </summary>
  4078. public const int SWP_ASYNCWINDOWPOS = 0x4000;
  4079. /// <summary>
  4080. ///
  4081. /// </summary>
  4082. public const int SWP_NOMOVE = 0x2; //H2
  4083. /// <summary>
  4084. ///
  4085. /// </summary>
  4086. public const int SWP_NOSIZE = 0x1; //H1
  4087. /// <summary>
  4088. ///
  4089. /// </summary>
  4090. public const int SWP_NOCOPYBITS = 0x100;
  4091. /// <summary>
  4092. ///
  4093. /// </summary>
  4094. public const int SWP_NOREPOSITION = SWP_NOOWNERZORDER;
  4095. /// <summary>
  4096. ///
  4097. /// </summary>
  4098. public const int WM_CLOSE = 0x10;
  4099. /// <summary>
  4100. ///
  4101. /// </summary>
  4102. public const int WS_CHILD = 0x40000000;
  4103. /// <summary>
  4104. ///
  4105. /// </summary>
  4106. public const int WS_BORDER = 0x00800000; //window with border
  4107. /// <summary>
  4108. ///
  4109. /// </summary>
  4110. public const int WS_DLGFRAME = 0x00400000; //window with double border but no title
  4111. // Extended Window Styles
  4112. /// <summary>
  4113. ///
  4114. /// </summary>
  4115. public static int WS_EX_MDICHILD = 0x40;
  4116. /// <summary>
  4117. ///
  4118. /// </summary>
  4119. public static int WS_EX_TOPMOST = 0x00000008;
  4120. /// <summary>
  4121. ///
  4122. /// </summary>
  4123. public static int WS_EX_TRANSPARENT = 0x00000020;
  4124. /// <summary>
  4125. ///
  4126. /// </summary>
  4127. public static int WS_EX_TOOLWINDOW = 0x00000080;
  4128. /// <summary>
  4129. ///
  4130. /// </summary>
  4131. public static int WS_EX_WINDOWEDGE = 0x00000100;
  4132. /// <summary>
  4133. ///
  4134. /// </summary>
  4135. public static int WS_EX_CLIENTEDGE = 0x00000200;
  4136. /// <summary>
  4137. ///
  4138. /// </summary>
  4139. public const int SW_HIDE = 0;
  4140. /// <summary>
  4141. ///
  4142. /// </summary>
  4143. public const int SW_SHOWNORMAL = 1;
  4144. /// <summary>
  4145. ///
  4146. /// </summary>
  4147. public const int SW_SHOWMINIMIZED = 2;
  4148. /// <summary>
  4149. ///
  4150. /// </summary>
  4151. public const int SW_SHOWMAXIMIZED = 3;
  4152. /// <summary>
  4153. ///
  4154. /// </summary>
  4155. public const int SW_SHOWNOACTIVATE = 4;
  4156. /// <summary>
  4157. ///
  4158. /// </summary>
  4159. public const int SW_RESTORE = 9;
  4160. /// <summary>
  4161. ///
  4162. /// </summary>
  4163. public const int SW_SHOWDEFAULT = 10;
  4164. #endregion
  4165. }
  4166. #endregion
  4167. #region 静态类)DataTable导出到Excel文件
  4168. /// <summary>
  4169. /// (静态类)DataTable导出到Excel文件
  4170. /// </summary>
  4171. public class ExportToExcel
  4172. {
  4173. /// <summary>
  4174. /// 把DataTable的数据导出到Excel文件中
  4175. /// </summary>
  4176. /// <param name="_dataTable">要导出的数据表</param>
  4177. /// <param name="_fileName">保存的Excel文件名</param>
  4178. /// <returns>是否导出成功</returns>
  4179. public static string dataTableExportToExcel_cell(ref DataTable _dataTable, string _fileName)
  4180. {
  4181. if (_dataTable == null) { return null; }
  4182. SuperTools.UC_EmbedExcelIntoWinFormNoDLL uc1 = new UC_EmbedExcelIntoWinFormNoDLL();
  4183. uc1.AppExcel_Open(null, false);
  4184. string strErr = null;
  4185. try
  4186. {
  4187. //写入字段名的信息
  4188. for (int i = 0; i < _dataTable.Columns.Count; i++)
  4189. {
  4190. uc1.SetCell_Value(1, i + 1, _dataTable.Columns[i].Caption); //写第一行内容为dataTable的字段名
  4191. }
  4192. //写入表中数据内容
  4193. for (int i = 0; i < _dataTable.DefaultView.Count; i++)
  4194. {
  4195. for (int col = 0; col < _dataTable.Columns.Count; col++)
  4196. {
  4197. uc1.SetCell_Value(i + 2, col + 1, _dataTable.DefaultView[i][col].ToString()); //转化为文本再写到excel当中
  4198. }
  4199. }
  4200. //uc1.App_ExcelSave(_fileName);
  4201. strErr = null;
  4202. }
  4203. catch (Exception operExce)
  4204. {
  4205. strErr = "写入表中数据!错误原因:" + operExce.Message;
  4206. }
  4207. finally
  4208. {
  4209. uc1.AppExcel_Exit();
  4210. }
  4211. return strErr;
  4212. }
  4213. /// <summary>
  4214. /// 把DataTable的数据导出到Excel文件中
  4215. /// </summary>
  4216. /// <param name="_dataTable">要导出的数据表</param>
  4217. /// <param name="_fileName">保存的Excel文件名</param>
  4218. /// <returns>是否导出成功</returns>
  4219. public static string dataTableExportToExcel_Range(ref DataTable _dataTable, string _fileName)
  4220. {
  4221. if (_dataTable == null) { return null; }
  4222. SuperTools.UC_EmbedExcelIntoWinFormNoDLL uc1 = new UC_EmbedExcelIntoWinFormNoDLL();
  4223. uc1.AppExcel_Open(null, false);
  4224. string strErr = null;
  4225. try
  4226. {
  4227. #region //写入字段名的信息
  4228. ////获取A1单元格所在区域
  4229. string BeginPoint = "A1";
  4230. string EndPoint = Convert.ToString(Convert.ToChar(64 + _dataTable.Columns.Count)) + "1";
  4231. int rows = 1;
  4232. int columns = _dataTable.Columns.Count;
  4233. string[,] Array_strHeadName_Value = new string[rows, columns]; //赋值:数值类型=string
  4234. for (int i = 0; i < rows; i++) //第一行
  4235. {
  4236. for (int j = 0; j < columns; j++)
  4237. {
  4238. Array_strHeadName_Value[i, j] = _dataTable.Columns[j].Caption; //字段名
  4239. }
  4240. }
  4241. uc1.SetRangeArray_Value(BeginPoint, EndPoint, Array_strHeadName_Value);
  4242. #endregion
  4243. //**********************************
  4244. #region 写入表中数据内容 //excel的其他行的Range中填充数据
  4245. string BeginPoint_1 = "A2";
  4246. string EndPoint_1 = Convert.ToString(Convert.ToChar(64 + _dataTable.Columns.Count)) + (_dataTable.Rows.Count + 1).ToString().Trim();
  4247. int rows_1 = _dataTable.Rows.Count;
  4248. int columns_1 = _dataTable.Columns.Count;
  4249. string[,] Array_string_Value = new string[rows_1, columns_1]; //赋值:数值类型=string
  4250. for (int y = 0; y < _dataTable.Rows.Count; y++)
  4251. {
  4252. for (int x = 0; x < _dataTable.Columns.Count; x++)
  4253. {
  4254. Array_string_Value[y, x] = _dataTable.Rows[y][x].ToString();
  4255. }
  4256. }
  4257. uc1.SetRangeArray_Value(BeginPoint_1, EndPoint_1, Array_string_Value);
  4258. #endregion
  4259. uc1.AppExcel_SaveAs(_fileName);
  4260. strErr = null;
  4261. }
  4262. catch (Exception operExce)
  4263. {
  4264. strErr = "写入表中数据!错误原因:" + operExce.Message;
  4265. }
  4266. finally
  4267. {
  4268. uc1.AppExcel_Exit();
  4269. }
  4270. return strErr;
  4271. }
  4272. /// <summary>
  4273. /// 把DataTable的数据导出到Excel文件中 测试
  4274. /// </summary>
  4275. /// <param name="w2"></param>
  4276. /// <param name="fileName"></param>
  4277. /// <returns></returns>
  4278. public static string dataTableExportToExcel_Range_x(DataTable w2, string fileName)
  4279. {
  4280. object MyApp;
  4281. object MyBook;
  4282. object MyBooks;
  4283. object MySheet;
  4284. object MySheets;
  4285. object MyRange;
  4286. object[] MyParameters;
  4287. //Type MyClassType;
  4288. if (w2 == null || w2.Rows.Count == 0)
  4289. {
  4290. string strErr = "dataTable为空 或 dataTable表中无数据";
  4291. return strErr;
  4292. }
  4293. try
  4294. {
  4295. // 获取Excel类型并建立其实例
  4296. Type MyClassType = Type.GetTypeFromProgID("Excel.Application");
  4297. if (MyClassType == null)
  4298. {
  4299. string strErr = "本计算机无Excel.Application";
  4300. return strErr;
  4301. }
  4302. MyApp = Activator.CreateInstance(MyClassType);
  4303. if (MyApp == null)
  4304. {
  4305. string strErr = "本计算机的Excel.Application无法正常使用!";
  4306. return strErr;
  4307. }
  4308. //获取Workbook集
  4309. MyBooks = MyApp.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, MyApp, null);
  4310. //添加一个新的Workbook
  4311. MyBook = MyBooks.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, MyBooks, null);
  4312. //获取Sheet集
  4313. MySheets = MyBook.GetType().InvokeMember("Worksheets", BindingFlags.GetProperty, null, MyBook, null);
  4314. //获取第一个Sheet对象
  4315. MyParameters = new Object[1] { 1 };
  4316. MySheet = MySheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, MySheets, MyParameters);
  4317. try
  4318. {
  4319. #region //写入字段名的信息
  4320. ////获取A1单元格所在区域
  4321. MyParameters = new object[1];
  4322. MyParameters[0] = "A1:" + Convert.ToString(Convert.ToChar(64 + w2.Columns.Count)) + "1"; //定义excel的第一行的Range
  4323. MyRange = MySheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, MySheet, MyParameters); //
  4324. //**********************************
  4325. //excel的第一行的Range中填充数据,该数据=dataTable的字段名
  4326. object[] objHeaders = new Object[w2.Columns.Count];
  4327. MyParameters = new object[1];
  4328. // objHeaders[0] = w2.Columns[1].ToString();
  4329. for (int i = 0; i < w2.Columns.Count; i++)
  4330. {
  4331. //objHeaders[i] = w2.Columns[i].ToString(); //字段名
  4332. objHeaders[i] = w2.Columns[i].Caption; //字段名
  4333. }
  4334. MyParameters[0] = objHeaders;
  4335. MyRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, MyRange, MyParameters);//写字段名
  4336. #endregion
  4337. //**********************************
  4338. #region 写入表中数据内容
  4339. //excel的其他行的Range中填充数据
  4340. MyParameters = new object[2];
  4341. MyParameters[0] = "A2:" + Convert.ToString(Convert.ToChar(64 + w2.Columns.Count)) + (w2.Rows.Count + 1).ToString().Trim();
  4342. MyParameters[1] = Missing.Value;
  4343. MyRange = MySheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, MySheet, MyParameters);
  4344. Object[,] MyData = new Object[w2.Rows.Count, w2.Columns.Count];
  4345. for (int y = 0; y < w2.Rows.Count; y++)
  4346. {
  4347. for (int x = 0; x < w2.Columns.Count; x++)
  4348. {
  4349. if (true) //(A3.Contains(ii))
  4350. {
  4351. MyData[y, x] = w2.Rows[y][x];
  4352. }
  4353. //else
  4354. //{
  4355. // MyData[ll, ii] = "'" + w2.Rows[ll][ii].ToString();
  4356. //}
  4357. }
  4358. }
  4359. MyParameters = new object[1];
  4360. MyParameters[0] = MyData;
  4361. MyRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, MyRange, MyParameters);
  4362. #endregion
  4363. ////MyParameters = new object[1];
  4364. //////启动 Excel
  4365. ////MyParameters[0] = true;
  4366. ////MyApp.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, MyApp, MyParameters);
  4367. ////MyApp.GetType().InvokeMember("UserControl", BindingFlags.SetProperty, null, MyApp, MyParameters);
  4368. }
  4369. catch (Exception ex)
  4370. {
  4371. string strErr = "操作App内容出错!错误原因:" + ex.Message;
  4372. return strErr;
  4373. }
  4374. finally
  4375. {
  4376. //不提示保存
  4377. MyParameters = new Object[1] { false };
  4378. MyApp.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, MyApp, MyParameters);
  4379. //保存文件并退出
  4380. MyParameters = new Object[1] { fileName };
  4381. MyBook.GetType().InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, MyBook, MyParameters);
  4382. MyApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, MyApp, null);
  4383. //System.Runtime.InteropServices.Marshal.ReleaseComObject(objCells);
  4384. System.Runtime.InteropServices.Marshal.ReleaseComObject(MySheet);
  4385. GC.GetTotalMemory(true);
  4386. System.Runtime.InteropServices.Marshal.ReleaseComObject(MySheets);
  4387. GC.GetTotalMemory(true);
  4388. System.Runtime.InteropServices.Marshal.ReleaseComObject(MyBook);
  4389. GC.GetTotalMemory(true);
  4390. System.Runtime.InteropServices.Marshal.ReleaseComObject(MyBooks);
  4391. GC.GetTotalMemory(true);
  4392. System.Runtime.InteropServices.Marshal.ReleaseComObject(MyApp);
  4393. GC.GetTotalMemory(true);
  4394. }
  4395. return null;
  4396. }
  4397. catch (Exception appExce)
  4398. {
  4399. string strErr = "操作App出错!错误原因:" + appExce.Message;
  4400. return strErr;
  4401. }
  4402. }
  4403. /// <summary>
  4404. /// 另外一种方法:把DataTable的数据导出到XML/Excel文件中 带格式
  4405. /// </summary>
  4406. /// <param name="_DataTable"></param>
  4407. /// <param name="fileName"></param>
  4408. public static void dataTableExportToExcelXml(DataTable _DataTable, string fileName)
  4409. {
  4410. System.IO.StreamWriter excelDoc;
  4411. excelDoc = new System.IO.StreamWriter(fileName);
  4412. const string startExcelXML = "<xml version>\r\n<Workbook " +
  4413. "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
  4414. " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
  4415. "xmlns:x=\"urn:schemas- microsoft-com:office:" +
  4416. "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
  4417. "office:spreadsheet\">\r\n <Styles>\r\n " +
  4418. "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
  4419. "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
  4420. "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
  4421. "\r\n <Protection/>\r\n </Style>\r\n " +
  4422. "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
  4423. "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
  4424. "<Style ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
  4425. " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
  4426. "ss:ID=\"Decimal\">\r\n <NumberFormat " +
  4427. "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
  4428. "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
  4429. "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
  4430. "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
  4431. "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
  4432. "</Styles>\r\n ";
  4433. const string endExcelXML = "</Workbook>";
  4434. int rowCount = 0;
  4435. int sheetCount = 1;
  4436. /*
  4437. <xml version>
  4438. <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  4439. xmlns:o="urn:schemas-microsoft-com:office:office"
  4440. xmlns:x="urn:schemas-microsoft-com:office:excel"
  4441. xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
  4442. <Styles>
  4443. <Style ss:ID="Default" ss:Name="Normal">
  4444. <Alignment ss:Vertical="Bottom"/>
  4445. <Borders/>
  4446. <Font/>
  4447. <Interior/>
  4448. <NumberFormat/>
  4449. <Protection/>
  4450. </Style>
  4451. <Style ss:ID="BoldColumn">
  4452. <Font x:Family="Swiss" ss:Bold="1"/>
  4453. </Style>
  4454. <Style ss:ID="StringLiteral">
  4455. <NumberFormat ss:Format="@"/>
  4456. </Style>
  4457. <Style ss:ID="Decimal">
  4458. <NumberFormat ss:Format="0.0000"/>
  4459. </Style>
  4460. <Style ss:ID="Integer">
  4461. <NumberFormat ss:Format="0"/>
  4462. </Style>
  4463. <Style ss:ID="DateLiteral">
  4464. <NumberFormat ss:Format="mm/dd/yyyy;@"/>
  4465. </Style>
  4466. </Styles>
  4467. <Worksheet ss:Name="Sheet1">
  4468. </Worksheet>
  4469. </Workbook>
  4470. */
  4471. excelDoc.Write(startExcelXML);
  4472. excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
  4473. excelDoc.Write("<Table>");
  4474. excelDoc.Write("<Row>");
  4475. for (int x = 0; x < _DataTable.Columns.Count; x++)
  4476. {
  4477. excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
  4478. excelDoc.Write(_DataTable.Columns[x].ColumnName);
  4479. excelDoc.Write("</Data></Cell>");
  4480. }
  4481. excelDoc.Write("</Row>");
  4482. foreach (DataRow x in _DataTable.Rows)
  4483. {
  4484. rowCount++;
  4485. //if the number of rows is > 64000 create a new page to continue output
  4486. if (rowCount == 64000)
  4487. {
  4488. rowCount = 0;
  4489. sheetCount++;
  4490. excelDoc.Write("</Table>");
  4491. excelDoc.Write(" </Worksheet>");
  4492. excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
  4493. excelDoc.Write("<Table>");
  4494. }
  4495. excelDoc.Write("<Row>"); //ID=" + rowCount + "
  4496. for (int y = 0; y < _DataTable.Columns.Count; y++)
  4497. {
  4498. System.Type rowType;
  4499. rowType = x[y].GetType();
  4500. switch (rowType.ToString())
  4501. {
  4502. case "System.String":
  4503. string XMLstring = x[y].ToString();
  4504. XMLstring = XMLstring.Trim();
  4505. XMLstring = XMLstring.Replace("&", "&");
  4506. XMLstring = XMLstring.Replace(">", ">");
  4507. XMLstring = XMLstring.Replace("<", "<");
  4508. excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
  4509. "<Data ss:Type=\"String\">");
  4510. excelDoc.Write(XMLstring);
  4511. excelDoc.Write("</Data></Cell>");
  4512. break;
  4513. case "System.DateTime":
  4514. //Excel has a specific Date Format of YYYY-MM-DD followed by
  4515. //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
  4516. //The Following Code puts the date stored in XMLDate
  4517. //to the format above
  4518. DateTime XMLDate = (DateTime)x[y];
  4519. string XMLDatetoString = ""; //Excel Converted Date
  4520. XMLDatetoString = XMLDate.Year.ToString() +
  4521. "-" +
  4522. (XMLDate.Month < 10 ? "0" +
  4523. XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
  4524. "-" +
  4525. (XMLDate.Day < 10 ? "0" +
  4526. XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
  4527. "T" +
  4528. (XMLDate.Hour < 10 ? "0" +
  4529. XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
  4530. ":" +
  4531. (XMLDate.Minute < 10 ? "0" +
  4532. XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
  4533. ":" +
  4534. (XMLDate.Second < 10 ? "0" +
  4535. XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
  4536. ".000";
  4537. excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
  4538. "<Data ss:Type=\"DateTime\">");
  4539. excelDoc.Write(XMLDatetoString);
  4540. excelDoc.Write("</Data></Cell>");
  4541. break;
  4542. case "System.Boolean":
  4543. excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
  4544. "<Data ss:Type=\"String\">");
  4545. excelDoc.Write(x[y].ToString());
  4546. excelDoc.Write("</Data></Cell>");
  4547. break;
  4548. case "System.Int16":
  4549. case "System.Int32":
  4550. case "System.Int64":
  4551. case "System.Byte":
  4552. excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
  4553. "<Data ss:Type=\"Number\">");
  4554. excelDoc.Write(x[y].ToString());
  4555. excelDoc.Write("</Data></Cell>");
  4556. break;
  4557. case "System.Decimal":
  4558. case "System.Double":
  4559. excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
  4560. "<Data ss:Type=\"Number\">");
  4561. excelDoc.Write(x[y].ToString());
  4562. excelDoc.Write("</Data></Cell>");
  4563. break;
  4564. case "System.DBNull":
  4565. excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
  4566. "<Data ss:Type=\"String\">");
  4567. excelDoc.Write("");
  4568. excelDoc.Write("</Data></Cell>");
  4569. break;
  4570. default:
  4571. throw (new Exception(rowType.ToString() + " not handled."));
  4572. }
  4573. }
  4574. excelDoc.Write("</Row>");
  4575. }
  4576. excelDoc.Write("</Table>");
  4577. excelDoc.Write(" </Worksheet>");
  4578. excelDoc.Write(endExcelXML);
  4579. excelDoc.Close();
  4580. }
  4581. }
  4582. #endregion
  4583. #region (静态类)DataTable的工具类
  4584. /// <summary>
  4585. /// (静态类)DataTable的工具类
  4586. /// </summary>
  4587. public class DataTableTools
  4588. {
  4589. /// <summary>
  4590. /// Hashtable的排序
  4591. /// </summary>
  4592. /// <param name="_HasTable">Hashtable的名字</param>
  4593. /// <returns> System.Collections.ArrayList</returns>
  4594. public static System.Collections.ArrayList HashTable_To_Sort(System.Collections.Hashtable _HasTable)
  4595. {
  4596. //根据选择的行的ID号,读取其相应的数据
  4597. System.Collections.ArrayList akeys = new System.Collections.ArrayList(_HasTable.Keys);
  4598. akeys.Sort(); //按键值字母顺序进行排序
  4599. foreach (int str_skey in akeys)
  4600. {
  4601. Console.Write(str_skey + ":");
  4602. Console.WriteLine(_HasTable[str_skey]);//排序后输出
  4603. }
  4604. return akeys;
  4605. }
  4606. /// <summary>
  4607. /// 将目标Hashtable转换成DataTable返回
  4608. /// </summary>
  4609. /// <param name="HasTable">目标Hashtable</param>
  4610. /// <returns>转换后的DataTable</returns>
  4611. public static DataTable HashTable_To_Table(System.Collections.Hashtable HasTable)
  4612. {
  4613. try
  4614. {
  4615. DataTable rtn_Table = new DataTable("HASHTABLE");
  4616. DataColumn KeyColumn = new DataColumn("KEY", typeof(object));
  4617. DataColumn ValueColumn = new DataColumn("VALUE", typeof(object));
  4618. rtn_Table.Columns.Add(KeyColumn);
  4619. rtn_Table.Columns.Add(ValueColumn);
  4620. rtn_Table.AcceptChanges();
  4621. System.Collections.IDictionaryEnumerator Has = HasTable.GetEnumerator();
  4622. while (Has.MoveNext())
  4623. {
  4624. DataRow nRow = rtn_Table.NewRow();
  4625. nRow["KEY"] = Has.Key;
  4626. nRow["VALUE"] = Has.Value;
  4627. rtn_Table.Rows.Add(nRow);
  4628. }
  4629. rtn_Table.AcceptChanges();
  4630. return rtn_Table;
  4631. }
  4632. catch (System.Exception ex)
  4633. {
  4634. Console.WriteLine(ex.ToString());
  4635. return null;
  4636. }
  4637. }
  4638. /// <summary>
  4639. /// Hashtable按键值字母顺序进行排序
  4640. /// </summary>
  4641. /// <param name="_ht_1"></param>
  4642. /// <returns></returns>
  4643. public static DataTable SetHashtablekeysSort(System.Collections.Hashtable _ht_1)
  4644. {
  4645. DataTable myDataTable = new DataTable();
  4646. //*********************
  4647. System.Collections.ArrayList akeys = new System.Collections.ArrayList(_ht_1.Keys); //别忘了导入System.Collections
  4648. akeys.Sort(); //按键值字母顺序进行排序
  4649. //*****************************************
  4650. myDataTable = SuperTools.DataTableTools.HashTable_To_Table(_ht_1);
  4651. return myDataTable;
  4652. }
  4653. /// <summary>
  4654. /// 将目标DataTable 转换成Hashtable返回
  4655. /// </summary>
  4656. /// <param name="_DataTable">目标Hashtable</param>
  4657. /// <returns>转换后的Hashtable</returns>
  4658. public static System.Collections.Hashtable Table_To_HashTable(DataTable _DataTable)
  4659. {
  4660. System.Collections.Hashtable _Hashtable = null;
  4661. return _Hashtable;
  4662. }
  4663. ///// <summary>
  4664. ///// 动态更新标的行数,根据新的行数动态更新
  4665. ///// </summary>
  4666. ///// <param name="table">目标DataTable</param>
  4667. ///// <param name="newRowCount">新的行数</param>
  4668. //public static void SetTableRows(ref DataTable table, int newRowCount)
  4669. //{
  4670. // int oldRowCount = table.Rows.Count;
  4671. // if (oldRowCount != newRowCount)
  4672. // {
  4673. // int absCount = Math.Abs(oldRowCount - newRowCount);
  4674. // if (oldRowCount > newRowCount)
  4675. // {
  4676. // for (int i = oldRowCount - 1; i >= absCount; i--)
  4677. // {
  4678. // table.Rows[i].Delete();
  4679. // }
  4680. // }
  4681. // else
  4682. // {
  4683. // object[] ColumnValue = new object[table.Columns.Count];
  4684. // for (int i = 0; i < absCount; i++)
  4685. // {
  4686. // table.Rows.Add(ColumnValue);
  4687. // }
  4688. // }
  4689. // }
  4690. //}
  4691. /// <summary>
  4692. /// 定义的table列的一个示例
  4693. /// </summary>
  4694. public static void Add_Columns_EG()
  4695. {
  4696. System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
  4697. ParaColumns.Add("ID|Int16"); //
  4698. ParaColumns.Add("日期|DateTime"); // System.DateTime
  4699. ParaColumns.Add("工资|Decimal"); //System.Decimal
  4700. ParaColumns.Add("电话|String"); //System.String
  4701. ParaColumns.Add("年龄|Int16"); //System.Int16
  4702. ParaColumns.Add("选择|Boolean"); //System .Boolean
  4703. System.Data.DataTable MyDataDataTable = new DataTable();
  4704. Add_Columns(ref MyDataDataTable, ParaColumns);
  4705. }
  4706. /// <summary>
  4707. /// 定义的table列
  4708. /// </summary>
  4709. /// <param name="_Table">目标DataTable</param>
  4710. /// <param name="_ParaColumns">增加的数列</param>
  4711. public static void Add_Columns(ref System.Data.DataTable _Table, System.Collections.ArrayList _ParaColumns)
  4712. {
  4713. for (int i = 0; i < _ParaColumns.Count; i++)
  4714. {
  4715. string[] strColumnsNameType = new string[2]; //字段名和字段类型
  4716. strColumnsNameType = ((string)_ParaColumns[i]).Split('|');
  4717. string strColumnsType = strColumnsNameType[1];
  4718. #region 设置字段名字和类型
  4719. System.Type MyType;
  4720. switch (strColumnsType)
  4721. {
  4722. //ParaColumns.Add("ID|Int16"); //
  4723. //ParaColumns.Add("日期|DateTime"); // System.DateTime
  4724. //ParaColumns.Add("工资|Decimal"); //System.Decimal
  4725. //ParaColumns.Add("电话|String"); //System.String
  4726. //ParaColumns.Add("年龄|Int16"); //System.Int16
  4727. //ParaColumns.Add("选择|Boolean"); //System .Boolean
  4728. case "String":
  4729. MyType = typeof(System.String);
  4730. break;
  4731. case "Boolean":
  4732. MyType = typeof(System.Boolean);
  4733. break;
  4734. case "Int16":
  4735. MyType = typeof(System.Int16);
  4736. break;
  4737. case "Decimal":
  4738. MyType = typeof(System.Decimal);
  4739. break;
  4740. case "DateTime":
  4741. MyType = typeof(System.DateTime);
  4742. break;
  4743. }
  4744. MyType = typeof(string);
  4745. #endregion 设置字段名字和类型
  4746. _Table.Columns.Add(strColumnsNameType[0], MyType);
  4747. //typeof(string);
  4748. //typeof(decimal);
  4749. //typeof(float);
  4750. //typeof(bool);
  4751. //typeof(byte);
  4752. //typeof(Double);
  4753. //typeof(System.String);
  4754. }
  4755. }
  4756. /// <summary>
  4757. /// 增加的table行
  4758. /// </summary>
  4759. /// <param name="_Table">目标DataTable</param>
  4760. /// <param name="_RowsCount">DataTable的行数</param>
  4761. public static void Add_Rows(ref System.Data.DataTable _Table, int _RowsCount)
  4762. {
  4763. //for (int i = 0; i < _IPCount; i++)
  4764. //{
  4765. // _Table.Rows.Add(new object[] { null, null, null, null, null, null, null, null, null, null, null });
  4766. //}
  4767. //**********
  4768. int oldRowCount = _Table.Rows.Count;
  4769. int NewRowCount = _RowsCount;
  4770. if (oldRowCount != NewRowCount)
  4771. {
  4772. int absCount = Math.Abs(oldRowCount - NewRowCount);
  4773. if (oldRowCount > NewRowCount)
  4774. {
  4775. for (int i = oldRowCount - 1; i >= absCount; i--)
  4776. {
  4777. _Table.Rows[i].Delete();
  4778. }
  4779. }
  4780. else
  4781. {
  4782. object[] ColumnValue = new object[_Table.Columns.Count];
  4783. for (int i = 0; i < absCount; i++)
  4784. {
  4785. _Table.Rows.Add(ColumnValue);
  4786. } //for
  4787. } //else
  4788. } //if
  4789. }
  4790. /// <summary>
  4791. /// 增加_Table行的一个实际示例(五种数据类型)
  4792. /// </summary>
  4793. /// <param name="_Table">目标DataTable</param>
  4794. /// <param name="_RowsCount">DataTable的行数</param>
  4795. public static void Add_Rows_EG(ref System.Data.DataTable _Table, int _RowsCount)
  4796. {
  4797. Random r = new Random();
  4798. object[] ColumnValue = new object[_Table.Columns.Count];
  4799. DateTime t = DateTime.Now; //取得当前系统时间
  4800. TimeSpan MySpan = new TimeSpan(1, 2, 3, 4); // 注意: TimeSpan(days, hours, minutes, seconds)
  4801. //t = t.Subtract(MySpan); //在当前时间上减上MySpan string ss = "2007-9-5 20:33:49";
  4802. for (int i = 0; i < _RowsCount; i++)
  4803. {
  4804. ColumnValue[0] = i;
  4805. ColumnValue[1] = t;
  4806. ColumnValue[2] = r.NextDouble() * 1000000;
  4807. ColumnValue[3] = RandomTelephone(r);
  4808. ColumnValue[4] = r.Next(100);
  4809. ColumnValue[5] = false;
  4810. _Table.Rows.Add(ColumnValue);
  4811. t = t.Add(MySpan); //在当前时间上加上上MySpan
  4812. //ColumnValue["ID"] = i;
  4813. //ColumnValue["日期"] = DateTime.Today.AddDays(i);
  4814. //ColumnValue["工资"] = r.NextDouble() * 1000000;
  4815. //ColumnValue["电话"] = RandomTelephone(r);
  4816. //ColumnValue["年龄"] = r.Next(100);
  4817. //ColumnValue["选择"] = false;
  4818. }
  4819. }
  4820. ///// <summary>
  4821. ///// 增加_Table行的一个实际示例(五种数据类型)
  4822. ///// </summary>
  4823. ///// <param name="_ObjectArray">待写入的值</param>
  4824. ///// <param name="_RowsCount">DataTable的行数</param>
  4825. /////
  4826. /// <summary>
  4827. /// 根据一个已有的空二维数组的 Object[,] ,填充随机数
  4828. /// </summary>
  4829. /// <param name="_ObjectArray">待写入已有的二维数组的Object[,]</param>
  4830. /// <returns>填充随机数的二维数组的 Object[,]</returns>
  4831. public static object[,] Get_ObjectArrayValue_Random(ref Object[,] _ObjectArray)
  4832. {
  4833. Random r = new Random();
  4834. DateTime t = DateTime.Now; //取得当前系统时间
  4835. TimeSpan MySpan = new TimeSpan(1, 2, 3, 4); // 注意: TimeSpan(days, hours, minutes, seconds)
  4836. //t = t.Subtract(MySpan); //在当前时间上减上MySpan string ss = "2007-9-5 20:33:49";
  4837. for (int i = 0; i < _ObjectArray.GetLength(0); i++) //行数
  4838. {
  4839. if (_ObjectArray.GetLength(1) >= 5)
  4840. {
  4841. _ObjectArray[i, 0] = i;
  4842. _ObjectArray[i, 1] = t;
  4843. _ObjectArray[i, 2] = r.NextDouble() * 1000000;
  4844. _ObjectArray[i, 3] = RandomTelephone(r);
  4845. _ObjectArray[i, 4] = r.Next(100);
  4846. _ObjectArray[i, 5] = false;
  4847. t = t.Add(MySpan); //在当前时间上加上上MySpan
  4848. }
  4849. }
  4850. return _ObjectArray;
  4851. }
  4852. /// <summary>
  4853. /// 根据行列数得到填充随机数的二维数组的 Object[,]
  4854. /// </summary>
  4855. /// <param name="_nRowsCount">行数</param>
  4856. /// <param name="_nColumnsCount">列数</param>
  4857. /// <returns>填充随机数的二维数组的 Object[,]</returns>
  4858. public static object[,] Get_ObjectArrayValue_EG(int _nRowsCount, int _nColumnsCount)
  4859. {
  4860. Random r = new Random();
  4861. object[,] obEG = new object[_nRowsCount, _nColumnsCount];
  4862. obEG = SuperTools.DataTableTools.Get_ObjectArrayValue_Random(ref obEG);
  4863. return obEG;
  4864. }
  4865. /// <summary>
  4866. /// 产生一个随机的字符
  4867. /// </summary>
  4868. /// <param name="r"></param>
  4869. /// <returns></returns>
  4870. private static string RandomTelephone(Random r)
  4871. {
  4872. //Random r = new Random();
  4873. System.Text.StringBuilder s = new System.Text.StringBuilder();
  4874. for (int i = 0; i < 11; i++)
  4875. s.Append(r.Next(10));
  4876. return s.ToString();
  4877. }
  4878. /// <summary>
  4879. /// 二维数组的 Object[,]转换成为DataTable 字段类型都为string
  4880. /// </summary>
  4881. /// <param name="_ObjectArray">二维数组的 Object[,]</param>
  4882. /// <param name="_bExistColumnsName">二维数组的 Object[,]是否包含字段名</param>
  4883. /// <returns></returns>
  4884. public static DataTable Get_DataTableFromObjectArray(ref Object[,] _ObjectArray, bool _bExistColumnsName)
  4885. {
  4886. DataTable dtTable1 = new DataTable();
  4887. if (_ObjectArray == null) { return null; }
  4888. if (!_bExistColumnsName)
  4889. {
  4890. System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
  4891. for (int i = 0; i < _ObjectArray.GetLength(1); i++) //列数
  4892. {
  4893. ParaColumns.Add("字段" + (i + 1).ToString() + "|String"); //System.String
  4894. }
  4895. Add_Columns(ref dtTable1, ParaColumns); //增加DataTabe列
  4896. Add_Rows(ref dtTable1, _ObjectArray.GetLength(0)); //:增加DataTabe行
  4897. for (int i = 0; i < _ObjectArray.GetLength(0); i++) //行数
  4898. {
  4899. for (int j = 0; j < _ObjectArray.GetLength(1); j++) //列数
  4900. {
  4901. dtTable1.Rows[i][j] = _ObjectArray[i, j];
  4902. }
  4903. }
  4904. }
  4905. else
  4906. {
  4907. System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
  4908. for (int i = 0; i < _ObjectArray.GetLength(1); i++) //列数
  4909. {
  4910. ParaColumns.Add(_ObjectArray[1, i].ToString() + "|String"); //System.String
  4911. }
  4912. Add_Columns(ref dtTable1, ParaColumns); //增加DataTabe列
  4913. Add_Rows(ref dtTable1, _ObjectArray.GetLength(0) - 1); //:增加DataTabe行
  4914. for (int i = 0; i < _ObjectArray.GetLength(0); i++) //行数
  4915. {
  4916. for (int j = 0; j < _ObjectArray.GetLength(1); j++) //列数
  4917. {
  4918. dtTable1.Rows[i][j] = _ObjectArray[i, j];
  4919. }
  4920. }
  4921. }
  4922. return dtTable1;
  4923. }
  4924. /// <summary>
  4925. /// 设置字段名字和类型 并且初始化行数,内容为空
  4926. /// </summary>
  4927. /// <param name="_Table">目标DataTable</param>
  4928. /// <param name="_ParaColumns">增加空内容到每一行</param>
  4929. ///<param name="_RowsCount">增加空内容到每一行</param>
  4930. public static void Set_Table_Columns_Rows(ref System.Data.DataTable _Table, System.Collections.ArrayList _ParaColumns, int _RowsCount)
  4931. {
  4932. Add_Columns(ref _Table, _ParaColumns);
  4933. Add_Rows(ref _Table, _RowsCount);
  4934. }
  4935. /// <summary>
  4936. /// 根据查询条件:刷选行(满足条件的行),返回新的DataTable
  4937. /// </summary>
  4938. /// <param name="_dt">源数据DataTable</param>
  4939. /// <param name="_strSelectRowsCondition">选择列的条件:刷选行(满足条件的行)</param>
  4940. /// <returns></returns>
  4941. public static DataTable GetNewDataTable(ref DataTable _dt, string _strSelectRowsCondition)
  4942. {
  4943. if (_dt == null)
  4944. {
  4945. return null;
  4946. }
  4947. //string strMyFilterCondition = "蒸汽";
  4948. //string Filter = "介质类型 = '" + strMyFilterCondition + "'";    //介质类型过滤
  4949. DataTable newdt = new DataTable();
  4950. newdt = _dt.Clone(); //创建同结构的表,但没有行数据 行数= 0;
  4951. try
  4952. {
  4953. DataRow[] rows = _dt.Select(_strSelectRowsCondition);
  4954. //DataRow[] rows = _dt.Select(_strCondition);
  4955. //for (int i = 0; i < rows.Length; i++)
  4956. //{
  4957. // newdt.ImportRow((DataRow)rows[i]);
  4958. //}
  4959. foreach (DataRow row in rows)
  4960. {
  4961. //newdt.Rows.Add(row.ItemArray); //ok
  4962. newdt.ImportRow(row); //ok
  4963. }
  4964. newdt.AcceptChanges();
  4965. }
  4966. catch //(Exception ex)
  4967. {
  4968. return null;
  4969. }
  4970. return newdt;//返回的查询结果
  4971. }
  4972. /// <summary>
  4973. /// 根据给定的列名,返回新的DataTable
  4974. /// </summary>
  4975. /// <param name="_dt">源数据DataTable</param>
  4976. /// <param name="_Column_1_Name">第一列的列名</param>
  4977. /// <param name="_Column_2_Name">第二列的列名</param>
  4978. /// <returns></returns>
  4979. public static DataTable GetNewDataTable(ref DataTable _dt, string _Column_1_Name, string _Column_2_Name)
  4980. {
  4981. if (_dt == null)
  4982. {
  4983. return null;
  4984. }
  4985. DataTable newdt = new DataTable();
  4986. System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
  4987. if (_dt.Columns.Contains(_Column_1_Name))
  4988. {
  4989. string clName = _Column_1_Name;
  4990. System.Type clType = _dt.Columns[_Column_1_Name].DataType;    //可能有问题
  4991. newdt.Columns.Add(clName, clType); //增加列
  4992. }
  4993. if (_dt.Columns.Contains(_Column_2_Name))
  4994. {
  4995. string clName = _Column_2_Name;
  4996. System.Type clType = _dt.Columns[_Column_2_Name].DataType;
  4997. newdt.Columns.Add(clName, clType); //增加列
  4998. }
  4999. Add_Rows(ref newdt, _dt.Rows.Count); //增加空行
  5000. //for (int i = 0; i < _dt.Rows.Count; i++)
  5001. //{
  5002. // newdt.Rows[i][_Column_1_Name] = _dt.Rows[i][_Column_1_Name];
  5003. // newdt.Rows[i][_Column_2_Name] = _dt.Rows[i][_Column_2_Name];
  5004. //}
  5005. for (int i = 0; i < _dt.Rows.Count; i++)
  5006. {
  5007. foreach (DataColumn NewColumn in newdt.Columns) ////新表中的每列
  5008. {
  5009. newdt.Rows[i][NewColumn.ColumnName] = _dt.Rows[i][NewColumn.ColumnName];
  5010. }
  5011. }
  5012. newdt.AcceptChanges();
  5013. return newdt;//返回的查询结果
  5014. }
  5015. /// <summary>
  5016. /// 根据给定的列名(数组),返回新的DataTable
  5017. /// </summary>
  5018. /// <param name="_dt">源数据DataTable</param>
  5019. /// <param name="ColumnsName">列名的数组</param>
  5020. /// <returns></returns>
  5021. public static DataTable GetNewDataTable(ref DataTable _dt, string[] ColumnsName)
  5022. {
  5023. if (_dt == null)
  5024. {
  5025. return null;
  5026. }
  5027. DataTable newdt = new DataTable();
  5028. System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
  5029. for (int i = 0; i < ColumnsName.Length; i++)
  5030. {
  5031. string clName = ColumnsName[i];
  5032. System.Type clType = _dt.Columns[ColumnsName[i]].DataType;    //可能有问题
  5033. newdt.Columns.Add(clName, clType); //增加列
  5034. }
  5035. Add_Rows(ref newdt, _dt.Rows.Count); //增加空行
  5036. //for (int i = 0; i < _dt.Rows.Count; i++)
  5037. //{
  5038. // newdt.Rows[i][_Column_1_Name] = _dt.Rows[i][_Column_1_Name];
  5039. // newdt.Rows[i][_Column_2_Name] = _dt.Rows[i][_Column_2_Name];
  5040. //}
  5041. for (int i = 0; i < _dt.Rows.Count; i++)
  5042. {
  5043. foreach (DataColumn NewColumn in newdt.Columns) ////新表中的每列
  5044. {
  5045. newdt.Rows[i][NewColumn.ColumnName] = _dt.Rows[i][NewColumn.ColumnName];
  5046. }
  5047. }
  5048. newdt.AcceptChanges();
  5049. return newdt;//返回的查询结果
  5050. }
  5051. /// <summary>
  5052. /// 复制数据,深度复制
  5053. /// </summary>
  5054. /// <param name="dataSourceRow">数据源,待复制的数据</param>
  5055. /// <param name="dataStruct">数据结构/表结构</param>
  5056. /// <returns>处理后的DataTable</returns>
  5057. public static DataTable CopyData(DataRow[] dataSourceRow, DataTable dataStruct)
  5058. {
  5059. DataTable dataTable = new DataTable();
  5060. //定义表结构
  5061. DataColumn col;
  5062. foreach (DataColumn column in dataStruct.Columns)
  5063. {
  5064. col = new DataColumn();
  5065. col.ColumnName = column.ColumnName;
  5066. col.DataType = column.DataType;
  5067. //add column
  5068. dataTable.Columns.Add(col);
  5069. }
  5070. foreach (DataRow row in dataSourceRow)
  5071. {
  5072. DataRow tempRow = dataTable.NewRow();
  5073. foreach (DataColumn column in dataStruct.Columns)
  5074. {
  5075. try
  5076. {
  5077. tempRow[column.ColumnName] = row[column.ColumnName];
  5078. }
  5079. catch
  5080. { continue; }
  5081. }
  5082. dataTable.Rows.Add(tempRow);
  5083. }
  5084. return dataTable;
  5085. }
  5086. }
  5087. #endregion
  5088. #region (静态类)操作文件的工具
  5089. /// <summary>
  5090. /// (静态类)操作文件的工具
  5091. /// </summary>
  5092. public class FileTools
  5093. {
  5094. /// <summary>
  5095. /// 列举出制定目录夹下的所有文件
  5096. /// </summary>
  5097. /// <param name="DirPath"></param>
  5098. /// <returns></returns>
  5099. public static string[] GetAllFilenNameByDir(string DirPath)
  5100. {
  5101. string[] FilesName = new string[System.IO.Directory.GetFiles(DirPath).Length];
  5102. int i = 0;
  5103. foreach (string file in System.IO.Directory.GetFiles(DirPath)) //列举出所有文件,添加到AL
  5104. {
  5105. FilesName[i] = file;
  5106. i = i + 1;
  5107. }
  5108. return FilesName;
  5109. }
  5110. /// <summary>
  5111. /// 测试
  5112. /// </summary>
  5113. /// <param name="DirPath"></param>
  5114. /// <returns></returns>
  5115. public static System.Collections.ArrayList GetAllFileByDir(string DirPath)
  5116. {
  5117. System.Collections.ArrayList AL = new System.Collections.ArrayList();
  5118. foreach (string file in System.IO.Directory.GetFiles(DirPath)) //列举出所有文件,添加到AL
  5119. {
  5120. AL.Add(file);
  5121. }
  5122. return AL;
  5123. //foreach (string dir in System.IO.Directory.GetDirectories(DirPath)) //列举出所有子文件夹,并对之调用GetAllFileByDir自己;
  5124. //{
  5125. // //GetAllFileByDir(dir, ref AL);
  5126. //}
  5127. // void GetAllFileByDir(string DirPath,ref ArrayList AL)
  5128. //{
  5129. // //列举出所有文件,添加到AL
  5130. // foreach(string file in Directory.GetFiles(DirPath))
  5131. // AL.Add(file);
  5132. // //列举出所有子文件夹,并对之调用GetAllFileByDir自己;
  5133. // foreach(string dir in Directory.GetDirectories(DirPath))
  5134. // GetAllFileByDir(dir,ref AL);
  5135. //}
  5136. }
  5137. /// <summary>
  5138. /// 得到待打开的文件名
  5139. /// </summary>
  5140. /// <param name="_FileType">=null为所有文件|xml类文件="xml"|Excel文件="xls"|word文件="doc"|文本文件="txt")执行文件="exe"|图形文件="jpg|C#类文件=cs|BIN文件=bin</param>
  5141. /// <returns></returns>
  5142. public static string GetFileOpenName(string _FileType)
  5143. {
  5144. string strFileName = "";
  5145. System.Windows.Forms.OpenFileDialog MyOpenFileDialog = new System.Windows.Forms.OpenFileDialog();
  5146. string strFilter = "所有文件(*.*)|*.*";
  5147. if (_FileType == null)
  5148. {
  5149. MyOpenFileDialog.Filter = strFilter; //当前目录的显示文件类型过滤
  5150. MyOpenFileDialog.FilterIndex = 1;
  5151. }
  5152. else
  5153. {
  5154. #region 文件类型的字符串
  5155. switch (_FileType.ToLower())
  5156. {
  5157. case "xml":
  5158. _FileType = "xml文件(*.xml)|*.xml";
  5159. break;
  5160. case "xls":
  5161. _FileType = "Excel文件(*.xls)|*.xls";
  5162. break;
  5163. case "doc":
  5164. _FileType = "word类文件(*.doc)|*.doc";
  5165. break;
  5166. case "cs":
  5167. _FileType = "C#类文件(*.cs)|*.cs";
  5168. break;
  5169. case "jpg":
  5170. _FileType = "图形文件(*.jpg)|*.jpg";
  5171. break;
  5172. case "txt":
  5173. _FileType = "文本文件(*.txt)|*.txt";
  5174. break;
  5175. case "exe":
  5176. _FileType = "执行文件(*.exe)|*.exe";
  5177. break;
  5178. case "bin":
  5179. _FileType = "BIN文件(*.bin)|*.bin";
  5180. break;
  5181. }
  5182. #endregion
  5183. strFilter = strFilter + "|" + _FileType;
  5184. MyOpenFileDialog.Filter = strFilter; //当前目录的显示文件类型过滤
  5185. MyOpenFileDialog.FilterIndex = 2;
  5186. }
  5187. if (MyOpenFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
  5188. {
  5189. return null;
  5190. }
  5191. else
  5192. {
  5193. strFileName = MyOpenFileDialog.FileName;
  5194. return strFileName;
  5195. }
  5196. }
  5197. /// <summary>
  5198. /// 得到待保存的文件名
  5199. /// </summary>
  5200. /// <param name="_FileType">xml类文件="xml"|Excel文件="xls"|word文件="doc"|文本文件="txt")执行文件="exe"|图形文件="jpg|C#类文件=cs|BIN文件=bin</param>
  5201. /// <returns></returns>
  5202. public static string GetFileSaveName(string _FileType)
  5203. {
  5204. string strFileName = "";
  5205. System.Windows.Forms.SaveFileDialog MySaveFileDialog = new System.Windows.Forms.SaveFileDialog();
  5206. string strFilter = "所有文件(*.*)|*.*";
  5207. if (_FileType == null)
  5208. {
  5209. MySaveFileDialog.Filter = strFilter; //当前目录的显示文件类型过滤
  5210. MySaveFileDialog.FilterIndex = 1;
  5211. }
  5212. else
  5213. {
  5214. #region 文件类型的字符串
  5215. switch (_FileType.ToLower())
  5216. {
  5217. case "xml":
  5218. _FileType = "xml文件(*.xml)|*.xml";
  5219. break;
  5220. case "xls":
  5221. _FileType = "Excel文件(*.xls)|*.xls";
  5222. break;
  5223. case "doc":
  5224. _FileType = "word类文件(*.doc)|*.doc";
  5225. break;
  5226. case "cs":
  5227. _FileType = "C#类文件(*.cs)|*.cs";
  5228. break;
  5229. case "jpg":
  5230. _FileType = "图形文件(*.jpg)|*.jpg";
  5231. break;
  5232. case "txt":
  5233. _FileType = "文本文件(*.txt)|*.txt";
  5234. break;
  5235. case "exe":
  5236. _FileType = "执行文件(*.exe)|*.exe";
  5237. break;
  5238. case "bin":
  5239. _FileType = "BIN文件(*.bin)|*.bin";
  5240. break;
  5241. }
  5242. #endregion
  5243. strFilter = strFilter + "|" + _FileType;
  5244. MySaveFileDialog.Filter = strFilter; //当前目录的显示文件类型过滤
  5245. MySaveFileDialog.FilterIndex = 2;
  5246. }
  5247. if (MySaveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
  5248. {
  5249. return null;
  5250. }
  5251. else
  5252. {
  5253. strFileName = MySaveFileDialog.FileName;
  5254. return strFileName;
  5255. }
  5256. }
  5257. /// <summary>
  5258. /// 文件改名
  5259. /// </summary>
  5260. /// <param name="_strOldFileName">老文件名</param>
  5261. /// <param name="_strPostfix">后缀</param>
  5262. /// <returns></returns>
  5263. public static string GetFileChangeName(string _strOldFileName, string _strPostfix)
  5264. {
  5265. //string _strFileName = Lonty.UC.GetFileNameString.SaveName("xls");
  5266. if (_strOldFileName == "") { return null; }
  5267. int x1 = _strOldFileName.LastIndexOf("\\");
  5268. string Path = _strOldFileName.Substring(0, x1 + 1);
  5269. string SaveFileName = _strOldFileName.Substring(x1 + 1, _strOldFileName.Length - x1 - 5) + _strPostfix;
  5270. string strFileTypeName = _strOldFileName.Substring(_strOldFileName.Length - 4, 4).ToLower();
  5271. SaveFileName = Path + SaveFileName + strFileTypeName;
  5272. return SaveFileName;
  5273. //if (myExcel_1.App_ExcelSave(SaveFileName))
  5274. //{
  5275. // MessageBox.Show("文件<" + SaveFileName + ">保存成功!");
  5276. //}
  5277. //else
  5278. //{
  5279. // MessageBox.Show("文件<" + SaveFileName + ">保存失败!");
  5280. //}
  5281. }
  5282. /// <summary>
  5283. /// 获取没有目录路径的文件名
  5284. /// </summary>
  5285. /// <param name="_strOldFileName"></param>
  5286. /// <param name="_b1">是否包含文件扩展名,true = 包含文件扩展名</param>
  5287. /// <returns>不含目录路径的文件名</returns>
  5288. public static string GetFileNameNoPath(string _strOldFileName, bool _b1)
  5289. {
  5290. if (_strOldFileName == "") { return null; }
  5291. try
  5292. {
  5293. int x1 = _strOldFileName.LastIndexOf("\\");
  5294. string Path = _strOldFileName.Substring(0, x1 + 1);
  5295. string SaveFileName = _strOldFileName.Substring(x1 + 1, _strOldFileName.Length - x1 - 5);
  5296. if (_b1)
  5297. {
  5298. string strFileTypeName = _strOldFileName.Substring(_strOldFileName.Length - 4, 4).ToLower();
  5299. SaveFileName = SaveFileName + strFileTypeName;
  5300. }
  5301. return SaveFileName;
  5302. }
  5303. catch { return null; }
  5304. }
  5305. /// <summary>
  5306. /// 把文件名中最后的的字符"PARAPOSDEF".改为"PARA" ,扩展名不变
  5307. /// </summary>
  5308. /// <param name="_strFileName"></param>
  5309. /// <returns></returns>
  5310. public static string GetFileReName_PARAPOSDEF_PARA(string _strFileName)
  5311. {
  5312. //string _strFileName = Lonty.UC.GetFileNameString.SaveName("xls");
  5313. if (_strFileName == "") { return null; }
  5314. int x1 = _strFileName.LastIndexOf("\\");
  5315. int x2 = _strFileName.LastIndexOf("PARAPOSDEF");
  5316. if (x2 == -1)
  5317. {
  5318. MessageBox.Show("打开的文件名中不包含PARAPOSDEF等字符,不符合规范!");
  5319. x2 = _strFileName.Length;
  5320. }
  5321. String Path = _strFileName.Substring(0, x1 + 1);
  5322. //String SaveFileName = strFileName.Substring(x1 + 1, x2 - x1 -5) + "_PARA.xml";
  5323. String SaveFileName = _strFileName.Substring(x1 + 1, x2 - x1 - 2) + "_PARA";
  5324. string strFileTypeName = _strFileName.Substring(_strFileName.Length - 4, 4).ToLower();
  5325. SaveFileName = SaveFileName + strFileTypeName;
  5326. SaveFileName = Path + SaveFileName;
  5327. return SaveFileName;
  5328. //if (myExcel_1.App_ExcelSave(SaveFileName))
  5329. //{
  5330. // MessageBox.Show("文件<" + SaveFileName + ">保存成功!");
  5331. //}
  5332. //else
  5333. //{
  5334. // MessageBox.Show("文件<" + SaveFileName + ">保存失败!");
  5335. //}
  5336. }
  5337. /// <summary>
  5338. /// 将字符串保存为文件(汉字显示方式),文件名在此方法中将打开输入文件名的对话框
  5339. /// </summary>
  5340. /// <param name="_strData">要保存的字符串数据</param>
  5341. /// <param name="_bAppend">true=在文件原有内容的基础上添加 false =先清空,再写</param>
  5342. /// <returns></returns>
  5343. public static bool StringToSaveTxtFile(string _strData, bool _bAppend)
  5344. {
  5345. if (_strData == "")
  5346. {
  5347. System.Windows.Forms.MessageBox.Show("内容为空,不保存");
  5348. return false;
  5349. }
  5350. string FileName = SuperTools.FileTools.GetFileSaveName("txt");
  5351. //如果文件名没有扩展名就加上的扩展名
  5352. if (FileName.Length < 4 || FileName.Substring(FileName.Length - 4, 4).ToLower() != ".txt")
  5353. {
  5354. FileName += ".txt";
  5355. }
  5356. //*************************************************************
  5357. try
  5358. {
  5359. //System.IO.Stream MyStream = System.IO.File.OpenWrite(fName);
  5360. //using (System.IO.StreamWriter MyWriter = new System.IO.StreamWriter(MyStream, Encoding.GetEncoding("gb2312")))
  5361. using (System.IO.StreamWriter MyWriter = new System.IO.StreamWriter(FileName, _bAppend, Encoding.GetEncoding("gb2312")))
  5362. {
  5363. //strData = richTextBoxFor_ultraGrid_Init.Text;
  5364. MyWriter.Write(_strData);
  5365. MyWriter.Close();
  5366. System.Windows.Forms.MessageBox.Show("OK!文件保存完毕");
  5367. return true;
  5368. }
  5369. }
  5370. catch (System.IO.IOException ex)
  5371. {
  5372. System.Windows.Forms.MessageBox.Show(ex.Message, "Simple Editor",
  5373. System.Windows.Forms.MessageBoxButtons.OK,
  5374. System.Windows.Forms.MessageBoxIcon.Exclamation);
  5375. return false;
  5376. }//try
  5377. catch (Exception exp)
  5378. {
  5379. System.Console.WriteLine("保存文件错误:" + exp.Message);
  5380. return false;
  5381. } //try
  5382. }
  5383. /// <summary>
  5384. /// 写数据包信息到BIN文件
  5385. /// </summary>
  5386. /// <param name="_byteData">要保存的Byte数组数据</param>
  5387. /// <param name="_UpdateCount">Bin文件计数 </param>
  5388. public static bool ByteToSaveBinFile(byte[] _byteData, long _UpdateCount)
  5389. {
  5390. if (_byteData == null)
  5391. {
  5392. return false;
  5393. }
  5394. string _RunPath = System.Environment.CurrentDirectory; //当前windows系统环境目录
  5395. _RunPath = System.AppDomain.CurrentDomain.BaseDirectory; //当前应用程序的目录
  5396. //string str8 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;//获取模块的完整路径。
  5397. try
  5398. {
  5399. if (System.IO.Directory.Exists(_RunPath + "\\log") == false)
  5400. {
  5401. System.IO.Directory.CreateDirectory(_RunPath + "\\log");
  5402. }
  5403. string FileName;
  5404. string strCurrentTime = System.DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_ms");
  5405. FileName = _RunPath + "\\log\\Log_" + _UpdateCount.ToString("00000") + "_" + strCurrentTime + ".Bin";
  5406. try
  5407. {
  5408. //System.IO.Stream MyStream = System.IO.File.OpenWrite(fName);
  5409. //using (System.IO.StreamWriter MyWriter = new System.IO.StreamWriter(MyStream, Encoding.GetEncoding("gb2312")))
  5410. //using (System.IO.StreamWriter MyWriter = new System.IO.StreamWriter(FileName, _bAppend, Encoding.GetEncoding("gb2312")))
  5411. using (System.IO.FileStream FileStreamInf = new System.IO.FileStream(FileName, System.IO.FileMode.OpenOrCreate))
  5412. {
  5413. FileStreamInf.Write(_byteData, 0, _byteData.Length);
  5414. FileStreamInf.Close();
  5415. //System.Windows.Forms.MessageBox.Show("OK!文件保存完毕");
  5416. return true;
  5417. }
  5418. }
  5419. catch (System.IO.IOException ex)
  5420. {
  5421. System.Windows.Forms.MessageBox.Show(ex.Message, "Lonty",
  5422. System.Windows.Forms.MessageBoxButtons.OK,
  5423. System.Windows.Forms.MessageBoxIcon.Exclamation);
  5424. return false;
  5425. }//try
  5426. catch (Exception exp)
  5427. {
  5428. System.Console.WriteLine("保存日志文件文件错误:" + exp.Message);
  5429. return false;
  5430. } //catch
  5431. }
  5432. catch (System.Exception exp)
  5433. {
  5434. System.Console.WriteLine("写LOG日志文件文件错误:" + exp.Message);
  5435. return false;
  5436. }
  5437. }
  5438. /// <summary>
  5439. /// 写日志信息到日志文件
  5440. /// </summary>
  5441. /// <param name="_strData">要保存的字符串数据</param>
  5442. /// <param name="_bAppend">true=在文件原有内容的基础上添加 false =先清空,再写 </param>
  5443. public static bool StringToSaveLogFile(string _strData, bool _bAppend)
  5444. {
  5445. if (_strData == "")
  5446. {
  5447. return false;
  5448. }
  5449. string _RunPath = System.Environment.CurrentDirectory; //当前windows系统环境目录
  5450. _RunPath = System.AppDomain.CurrentDomain.BaseDirectory; //当前应用程序的目录
  5451. //string str8 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;//获取模块的完整路径。
  5452. try
  5453. {
  5454. if (System.IO.Directory.Exists(_RunPath + "\\log") == false)
  5455. {
  5456. System.IO.Directory.CreateDirectory(_RunPath + "\\log");
  5457. }
  5458. string FileName;
  5459. string CurrentAppName = "";
  5460. if (_bAppend)
  5461. {
  5462. string s1 = System.Windows.Forms.Application.ExecutablePath;
  5463. CurrentAppName = SuperTools.FileTools.GetFileNameNoPath(s1, false);
  5464. }
  5465. else
  5466. {
  5467. CurrentAppName = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ms");
  5468. }
  5469. FileName = _RunPath + "\\log\\Log_" + CurrentAppName + ".log";
  5470. try
  5471. {
  5472. //System.IO.Stream MyStream = System.IO.File.OpenWrite(fName);
  5473. //using (System.IO.StreamWriter MyWriter = new System.IO.StreamWriter(MyStream, Encoding.GetEncoding("gb2312")))
  5474. using (System.IO.StreamWriter MyWriter = new System.IO.StreamWriter(FileName, _bAppend, Encoding.GetEncoding("gb2312")))
  5475. {
  5476. string strCurrentTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ms");
  5477. MyWriter.WriteLine(strCurrentTime + ":" + _strData);
  5478. MyWriter.WriteLine("--------------------------------------------------------------------------------");
  5479. MyWriter.WriteLine("\r\n");
  5480. MyWriter.Close();
  5481. //System.Windows.Forms.MessageBox.Show("OK!文件保存完毕");
  5482. return true;
  5483. }
  5484. }
  5485. catch (System.IO.IOException ex)
  5486. {
  5487. System.Windows.Forms.MessageBox.Show(ex.Message, "Lonty",
  5488. System.Windows.Forms.MessageBoxButtons.OK,
  5489. System.Windows.Forms.MessageBoxIcon.Exclamation);
  5490. return false;
  5491. }//try
  5492. catch (Exception exp)
  5493. {
  5494. System.Console.WriteLine("保存日志文件文件错误:" + exp.Message);
  5495. return false;
  5496. } //catch
  5497. }
  5498. catch (System.Exception exp)
  5499. {
  5500. System.Console.WriteLine("写LOG日志文件文件错误:" + exp.Message);
  5501. return false;
  5502. }
  5503. }
  5504. /// <summary>
  5505. /// <para>更改文件的只读属性,以便可以修改了内容的文件可以覆盖</para>
  5506. /// </summary>
  5507. /// <param name="filePath">目录路径The fully qualified path to the file.</param>
  5508. public static void ChangeFileAttributesToWritable(string filePath)
  5509. {
  5510. //namespace Microsoft.Practices.EnterpriseLibrary.Common
  5511. //ArgumentValidation.CheckForNullReference(filePath, "filePath");
  5512. if (!System.IO.File.Exists(filePath))
  5513. {
  5514. return;
  5515. }
  5516. System.IO.FileAttributes attributes = System.IO.File.GetAttributes(filePath);
  5517. System.IO.FileAttributes attr = attributes | System.IO.FileAttributes.ReadOnly;
  5518. if (attr == attributes)
  5519. {
  5520. attributes ^= System.IO.FileAttributes.ReadOnly;
  5521. System.IO.File.SetAttributes(filePath, attributes);
  5522. }
  5523. }
  5524. /// <summary>
  5525. /// <para>检查文件是否只读</para>
  5526. /// </summary>
  5527. /// <param name="filePath">目录路径The fully qualified path to the file.</param>
  5528. public static bool IsFileReadOnly(string filePath)
  5529. {
  5530. if (!System.IO.File.Exists(filePath))
  5531. {
  5532. return false;
  5533. }
  5534. System.IO.FileAttributes attributes = System.IO.File.GetAttributes(filePath);
  5535. System.IO.FileAttributes attr = attributes | System.IO.FileAttributes.ReadOnly;
  5536. if (attr == attributes)
  5537. {
  5538. return true;
  5539. }
  5540. return false;
  5541. }
  5542. /*
  5543. /// <summary>
  5544. /// <para>Creat a zero byte length file in the specified path.</para>
  5545. /// </summary>
  5546. /// <param name="filePath">
  5547. /// <para>The absolute path to the file to create.</para>
  5548. /// </param>
  5549. /// <exception cref="ArgumentNullException">
  5550. /// <para><paramref name="filePath"/> is a <see langword="null"/> reference (Nothing in Visual Basic).</para>
  5551. /// </exception>
  5552. /// <exception cref="UnauthorizedAccessException">
  5553. /// <para>The caller does not have the required permission.</para>para>
  5554. /// <para>-or-</para>
  5555. /// <para><paramref name="filePath"/> specified a file that is read-only.</para>
  5556. /// </exception>
  5557. /// <exception cref="ArgumentException">
  5558. /// <para><paramref name="filePath"/> is a zero-length string, contains only white space, or contains one or more invalid characters as defined by <see cref="Path.InvalidPathChars"/>.</para>
  5559. /// </exception>
  5560. /// </exception>
  5561. /// <exception cref="ArgumentNullException">
  5562. /// <para><paramref name="filePath"/> is in an invalid format.</para>
  5563. /// </exception>
  5564. /// <seealso cref="System.IO.File.Create(string)"/>
  5565. ///
  5566. */
  5567. /// <summary>
  5568. /// 创建空文件
  5569. /// </summary>
  5570. /// <param name="filePath"></param>
  5571. public static void CreateZeroByteFile(string filePath)
  5572. {
  5573. //namespace Microsoft.Practices.EnterpriseLibrary.Common
  5574. //ArgumentValidation.CheckForNullReference(filePath, "filePath");
  5575. using (System.IO.File.Create(filePath))
  5576. {
  5577. }
  5578. }
  5579. /// <summary>
  5580. /// 在程序中运行批处理命令
  5581. /// </summary>
  5582. /// <param name="strCMD"></param>
  5583. /// <param name="strCMD_s"></param>
  5584. public static void RunBATcommand(string strCMD, string strCMD_s)
  5585. {
  5586. //声明一个程序信息类
  5587. System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();
  5588. Info.FileName = strCMD; //设置外部程序名
  5589. Info.Arguments = strCMD_s; //设置外部程序的启动参数(命令行参数)为test.txt
  5590. Info.WorkingDirectory = "C:\\DataLog\\"; //设置外部程序工作目录为 C:\DataLog
  5591. System.Diagnostics.Process Proc; //声明一个程序类
  5592. try //启动外部程序
  5593. {
  5594. Proc = System.Diagnostics.Process.Start(Info);
  5595. }
  5596. catch (System.ComponentModel.Win32Exception e)
  5597. {
  5598. Console.WriteLine("系统找不到指定的批处理文件。\r{0}", e);
  5599. return;
  5600. }
  5601. Console.WriteLine("外部程序的开始执行时间:{0}", Proc.StartTime); //打印出外部程序的开始执行时间
  5602. Proc.WaitForExit(8000); //等待3秒钟
  5603. //如果这个外部程序没有结束运行则对其强行终止
  5604. if (Proc.HasExited == false)
  5605. {
  5606. Console.WriteLine("由主程序强行终止外部程序的运行!");
  5607. Proc.Kill();
  5608. }
  5609. else
  5610. {
  5611. Console.WriteLine("由外部程序正常退出!");
  5612. }
  5613. Console.WriteLine("外部程序的结束运行时间:{0}", Proc.ExitTime);
  5614. Console.WriteLine("外部程序在结束运行时的返回值:{0}", Proc.ExitCode);
  5615. }
  5616. }
  5617. #endregion
  5618. }