| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782 |
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Drawing;
- using System.Data;
- using System.Text;
- using System.Windows.Forms;
- using System.Reflection;
- using System.Runtime.InteropServices; //调用API
- namespace SuperTools
- {
- #region (动态类)嵌入excel.exe应用程序到c#(V2.0)的WinForm里面
- /// <summary>
- /// 嵌入excel.exe应用程序到c#(V2.0)的WinForm里面
- /// 作者:yuanshou.如有问题,请联系:yuanshou@21cn.com
- /// </summary>
- public partial class UC_EmbedExcelIntoWinFormNoDLL : UserControl
- {
- #region 控件本身生成
- /// <summary>
- /// 必需的设计器变量。
- /// </summary>
- private System.ComponentModel.IContainer components = null;
- /// <summary>
- /// 清理所有正在使用的资源。
- /// </summary>
- /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
- protected override void Dispose(bool disposing)
- {
- AppExcel_Exit(); //调用退出
- //*******************************
- //C:\Documents and Settings\Administrator\Application Data\Microsoft\Excel\Excel11.xlb
- string LoginName = System.Environment.UserName; //计算机名字
- string strExcelStyleFileName = "C:\\Documents and Settings\\" + LoginName + "\\Application Data\\Microsoft\\Excel\\Excel11.xlb";
- if (System.IO.File.Exists(strExcelStyleFileName) == true)
- {
- System.IO.File.Delete(strExcelStyleFileName);
- }
- //********************
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
- #region 组件设计器生成的代码
- /// <summary>
- /// 设计器支持所需的方法 - 不要
- /// 使用代码编辑器修改此方法的内容。
- /// </summary>
- private void InitializeComponent()
- {
- this.SuspendLayout();
- //
- // UC_EmbedExcelIntoWinFormNoDLL
- //
- this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.Name = "UC_EmbedExcelIntoWinFormNoDLL";
- this.Size = new System.Drawing.Size(149, 132);
- this.Load += new System.EventHandler(this.UC_EmbedExcelIntoWinFormNoDLL_Load);
- this.SizeChanged += new System.EventHandler(this.UC_EmbedExcelIntoWinFormNoDLL_SizeChanged);
- this.ResumeLayout(false);
- }
- #endregion
- #endregion
- private IntPtr appSubWinHandle = IntPtr.Zero; //打开excel.exe窗体的句柄
- /// <summary>
- /// 构造函数
- /// </summary>
- public UC_EmbedExcelIntoWinFormNoDLL()
- {
- InitializeComponent();
- }
- private void UC_EmbedExcelIntoWinFormNoDLL_Load(object sender, EventArgs e)
- {
- }
- private void UC_EmbedExcelIntoWinFormNoDLL_SizeChanged(object sender, EventArgs e)
- {
- ReDraw();
- }
- #region 操作 excel
- private object m_objApp;
- private object m_objBooks;
- private object m_objBook;
- private object m_objSheets;
- private object m_objSheet;
- private DateTime LateBindingExcelStartTime; //AppExcel 窗口启动时间
- private DateTime LateBindingExcelEndTime; //AppExcel 窗口打开完毕后的时间
- /// <summary>
- /// 文件打开
- /// </summary>
- /// <param name="_ExcelFileName">打开的文件名字,默认打开激活的sheet1</param>
- /// <param name="_bEmbedExcelIntoWinForm">是否显示excel.exe应用程序的界面</param>
- /// <returns></returns>
- public void AppExcel_Open(string _ExcelFileName, bool _bEmbedExcelIntoWinForm)
- {
- AppExcel_Open(_ExcelFileName, 1, _bEmbedExcelIntoWinForm);
- }
- /// <summary>
- /// 文件打开
- /// </summary>
- /// <param name="_ExcelOpenFileName">打开的文件名字</param>
- /// <param name="_ActivatorSheet">选择激活的sheet序号,从1开始</param>
- /// <param name="_bEmbedExcelIntoWinForm">是否显示excel.exe应用程序的界面</param>
- /// <returns></returns>
- public bool AppExcel_Open(string _ExcelOpenFileName, int _ActivatorSheet, bool _bEmbedExcelIntoWinForm)
- {
- //if (_FileName == null) { return false; }
- if (m_objApp != null & m_objBook != null)
- { this.AppExcel_Exit(); }
- #region 实例化m_objApp,并打开m_objApp
- LateBindingExcelStartTime = System.DateTime.Now; //开始时间
- this.m_objApp = this.Get_App(); //获取Excel类型并建立其实例
- this.m_objBooks = this.Get_Books(this.m_objApp); //获取Workbook集
- this.m_objBook = this.Get_Book(this.m_objBooks, _ExcelOpenFileName);
- this.m_objSheets = this.Get_Sheets(this.m_objBook); //获取Sheet集
- this.m_objSheet = this.Get_Sheet(this.m_objSheets, _ActivatorSheet); //获取一个Sheet对象
- LateBindingExcelEndTime = System.DateTime.Now; //结束时间
- #endregion
- #region 获取句柄,并嵌入窗体
- if (_bEmbedExcelIntoWinForm)
- {
- this.SetApp_Visible(this.m_objApp, _bEmbedExcelIntoWinForm); //显示excel程序的界面,只有显示,才能获取句柄
- //this.SetApp_ExcelWindowState(2); // excel.exe程序可见后,最小化窗口
- this.appSubWinHandle = GetExcelProcessHandle(this.LateBindingExcelStartTime, this.LateBindingExcelEndTime);
- #region 嵌入窗体
- if (this.appSubWinHandle != IntPtr.Zero) //打开Excel窗口,并嵌入到WinForm中
- {
- this.EmbedIntoWindows();
- //this.SetApp_ExcelWindowState(1); //嵌入完后,显示 EXCEL.EXE的窗口正常显示
- this.SetApp_EmbedExcelStyle(); //设置嵌入excel的显示式样:隐藏系统菜单和命令快捷键
- return true;
- }
- else
- {
- MessageBox.Show("不能获取WinHandle,请关闭重新打开!");
- return false;
- }
- #endregion
- }
- else
- {
- return false;
- }
- #endregion
- }
- #region late Bing 的方法 设置说明
- //为了获取返回值,必须指定 BindingFlags.Instance 或 BindingFlags.Static。
- //可以使用下列 BindingFlags 调用标志表示要对成员采取的操作:
- //CreateInstance,表示调用构造函数。忽略 name。对其他调用标志无效。
- //InvokeMethod,表示调用方法,而不调用构造函数或类型初始值设定项。对 SetField 或 SetProperty 无效。
- //GetField,表示获取字段值。对 SetField 无效。
- //SetField,表示设置字段值。对 GetField 无效。
- //GetProperty,表示获取属性。对 SetProperty 无效。
- //SetProperty 表示设置属性。对 GetProperty 无效。
- //BindingFlags,枚举类型 如下:
- //BindingFlags.Instance : 对象实例
- //BindingFlags.Static : 静态成员
- //BindingFlags.Public : 指可在搜索中包含公共成员
- //BindingFlags.NonPublic : 指可在搜索中包含非公共成员(即私有成员和受保护的成员)
- //BindingFlags.FlattenHierarchy : 指可包含层次结构上的静态成员
- //BindingFlags.IgnoreCase : 表示忽略 name 的大小写
- //BindingFlags.DeclaredOnly : 仅搜索 Type 上声明的成员,而不搜索被简单继承的成员
- //BindingFlags.CreateInstance : 表示调用构造函数。忽略 name。对其他调用标志无效
- //举例:
- //对执行方法的,用 BindingFlags.InvokeMethod 如 sheet.Activate(),book.close();
- //对获取/设置属性的用GetProperty/SetProperty
- //BindingFlags SetPropFlags = BindingFlags.SetProperty | BindingFlags.Static | BindingFlags.Public |
- // BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase | BindingFlags.CreateInstance;
- #endregion
- #region 获取Excel类型并建立其实例
- /// <summary>
- /// 获取Excel类型并建立其实例
- /// </summary>
- /// <returns>Excel实例</returns>
- private object Get_App()
- {
- Type objExcelType = Type.GetTypeFromProgID("Excel.Application"); //Excel.Application //Word.Application //PowerPoint.Application //Outlook.Application
- if (objExcelType == null)
- {
- string strErr = "本计算机无Excel.Application";
- System.Windows.Forms.MessageBox.Show(strErr);
- return null;
- }
- //新建一个Excel.exe的进程
- object _objApp = Activator.CreateInstance(objExcelType);
- if (_objApp == null)
- {
- string strErr = "本计算机的Excel.Application无法正常使用!";
- System.Windows.Forms.MessageBox.Show(strErr);
- return null;
- }
- else
- {
- return _objApp;
- }
- }
- /// <summary>
- /// 获取Workbook集
- /// </summary>
- /// <param name="_objApp"></param>
- /// <returns></returns>
- private object Get_Books(object _objApp)
- {
- if (_objApp == null) { return null; }
- object m_objBooks = _objApp.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, _objApp, null);
- return m_objBooks;
- }
- /// <summary>
- /// 添加一个新的Workbook 或者 打开一个已经存在的Workbook
- /// </summary>
- /// <param name="_objBooks"></param>
- /// <param name="_strFileName">打开的文件名,如果为null,则新打开</param>
- /// <returns></returns>
- private object Get_Book(object _objBooks, string _strFileName)
- {
- if (_objBooks == null) { return null; }
- object m_objBook = new object();
- if (_strFileName == null)
- {
- //添加一个新的Workbook
- m_objBook = _objBooks.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, _objBooks, null);
- }
- else
- {
- //打开一个已经存在的Workbook
- #region 打开参数
- object o_Filename = _strFileName; // "123";
- object o_UpdateLinks = System.Reflection.Missing.Value;
- object o_ReadOnly = System.Reflection.Missing.Value;
- object o_Format = System.Reflection.Missing.Value;
- object o_Password = System.Reflection.Missing.Value;
- object o_WriteResPassword = System.Reflection.Missing.Value;
- object o_IgnoreReadOnlyRecommended = System.Reflection.Missing.Value;
- object o_Origin = System.Reflection.Missing.Value;
- object o_Delimiter = System.Reflection.Missing.Value;
- object o_Editable = System.Reflection.Missing.Value;
- object o_Notify = System.Reflection.Missing.Value;
- object o_Converter = System.Reflection.Missing.Value;
- object o_AddToMru = System.Reflection.Missing.Value;
- object o_Local = System.Reflection.Missing.Value;
- object o_CorruptLoad = System.Reflection.Missing.Value;
- object[] m_Parameters_objBooksOpen = new Object[15];
- m_Parameters_objBooksOpen[0] = o_Filename;
- m_Parameters_objBooksOpen[1] = o_UpdateLinks;
- m_Parameters_objBooksOpen[2] = o_ReadOnly;
- m_Parameters_objBooksOpen[3] = o_Format;
- m_Parameters_objBooksOpen[4] = o_Password;
- m_Parameters_objBooksOpen[5] = o_WriteResPassword;
- m_Parameters_objBooksOpen[6] = o_IgnoreReadOnlyRecommended;
- m_Parameters_objBooksOpen[7] = o_Origin;
- m_Parameters_objBooksOpen[8] = o_Delimiter;
- m_Parameters_objBooksOpen[9] = o_Editable;
- m_Parameters_objBooksOpen[10] = o_Notify;
- m_Parameters_objBooksOpen[11] = o_Converter;
- m_Parameters_objBooksOpen[12] = o_AddToMru;
- m_Parameters_objBooksOpen[13] = o_Local;
- m_Parameters_objBooksOpen[14] = o_CorruptLoad;
- #endregion
- m_objBook = _objBooks.GetType().InvokeMember("Open", BindingFlags.InvokeMethod, null, _objBooks, m_Parameters_objBooksOpen);
- }
- return m_objBook;
- }
- /// <summary>
- /// 获取Sheet集
- /// </summary>
- /// <param name="_objBook"></param>
- /// <returns></returns>
- private object Get_Sheets(object _objBook)
- {
- if (_objBook == null) { return null; }
- object m_objSheets = _objBook.GetType().InvokeMember("Worksheets", BindingFlags.GetProperty, null, _objBook, null);
- return m_objSheets;
- }
- /// <summary>
- /// 获取其中一个Sheet
- /// </summary>
- /// <param name="_objSheets"></param>
- /// <param name="_ActivatorSheet"></param>
- /// <returns></returns>
- private object Get_Sheet(object _objSheets, int _ActivatorSheet)
- {
- if (_objSheets == null) { return null; }
- //object[] m_Parameters_ActivatorSheet = new Object[1] { 1 }; //第一个sheet:sheet1
- object[] m_Parameters_ActivatorSheet = new Object[1] { _ActivatorSheet }; //第一个sheet:sheet1
- object m_objSheet = _objSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, _objSheets, m_Parameters_ActivatorSheet);
- this.SetSheet_ChangeActivateSheet(_ActivatorSheet);
- return m_objSheet;
- }
- #endregion
- //得到Excel进程ID的MainWindowHandle
- private static IntPtr GetExcelProcessHandle(DateTime beforeTime, DateTime afterTime)
- {
- IntPtr appProcessHandle = IntPtr.Zero;
- System.Diagnostics.Process[] myProcesses;
- DateTime startTime;
- myProcesses = System.Diagnostics.Process.GetProcessesByName("Excel");
- //得不到Excel进程ID,暂时只能判断进程启动时间
- foreach (System.Diagnostics.Process myProcess in myProcesses)
- {
- startTime = myProcess.StartTime;
- if (startTime >= beforeTime && startTime <= afterTime)
- {
- //myProcess.Kill();
- appProcessHandle = myProcess.MainWindowHandle;
- //private
- }
- }
- return appProcessHandle;
- }
- /// <summary>
- /// 嵌入窗体时,设置execel.exe应用程序嵌入窗体里面的显示式样
- /// </summary>
- /// <returns>是否成功</returns>
- private bool SetApp_EmbedExcelStyle()
- {
- this.SetApp_Exit_EditMode();
- try
- {
- this.SetApp_DisplayStatusBar(false); //状态栏
- this.SetApp_DisplayFormulaBar(false); //编辑栏
- this.SetApp_DisplayAlerts(false); //警告提醒
- //this.SetApp_DisplayFullScreen(false); //全屏
- //this.SetApp_DisableAskAQuestionDropdown(true); //用户提问帮助栏
- //this.SetApp_DisableCustomize(true); //用户自己定义菜单
- //this.SetCommandBar_Cell_Enabled(true); //可以右键弹出浮动菜单
- //this.SetApp_Display_DisplayHeadings(false); //禁止行号列标
- ////this.SetSheet_ChangeActivateSheet(1); //指定激活第一个sheet
- this.SetCell_ActiveCell("A1"); //指定激活第一个cell单元格
- ////this.SetSheet_DisplaySheet1_hiddenElseAllSheets(true); //隐藏除sheet1以外的其他的sheet
- //////直接指定设定
- //////this.App_SetAppWorksheetMenuBarEnabled(false); //excel的系统主菜单
- //////this.SetCommandBarName_Enabled("Worksheet Menu Bar", false);
- //////this.SetCommandBarName_Enabled("Standard", false);
- //////this.SetCommandBarName_Enabled("Cell", true);
- ////////"Standard" "Formatting" "Envelope" "Task Pane" "Tables" "Ink" "System" ""
- //////this.SetCommandBarName_Visible("Standard", false);
- //////this.SetCommandBarName_Visible("Formatting", false);
- //////this.SetCommandBarName_Visible("Envelope", false);
- //////this.SetCommandBarName_Visible("Task Pane", false);
- //////*********************************************
- //枚举所有的系统下拉菜单和命令快捷键全部隐藏和不可用
- this.SetCommandBars_IEnumeratorCommandBarsName();
- //this.SetApp_ExcelSystemMenu_xiala(false);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("App设置显示式样有误!" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 退出excel.exe的编辑模式 Edit Mode
- /// </summary>
- public void SetApp_Exit_EditMode()
- {
- if (m_objApp == null) { return; }
- if (m_objSheet == null) { return; }
- while (true)
- {
- try
- {
- this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
- bool bAppReady = (bool)m_objApp.GetType().InvokeMember("Ready", BindingFlags.GetProperty, null, m_objApp, null);
- this.Cursor = System.Windows.Forms.Cursors.Arrow;
- break; //如果excel.exe退出了编辑模式则退出循环
- }
- catch
- {
- myWin32API.SetForegroundWindow(this.appSubWinHandle);
- myWin32API.SetFocus(this.appSubWinHandle);
- //System.Threading.Thread.Sleep(100);
- System.Windows.Forms.SendKeys.SendWait("{ESC}"); //发送ESC键
- //System.Windows.Forms.SendKeys.Send("{ESC}"); //发送ESC键
- //System.Threading.Thread.Sleep(100);
- }
- }
- }
- public void SetApp_Exit_OKMode()
- {
- if (m_objApp == null) { return; }
- if (m_objSheet == null) { return; }
- while (true)
- {
- try
- {
- this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
- bool bAppReady = (bool)m_objApp.GetType().InvokeMember("Ready", BindingFlags.GetProperty, null, m_objApp, null);
- this.Cursor = System.Windows.Forms.Cursors.Arrow;
- break; //如果excel.exe退出了编辑模式则退出循环
- }
- catch
- {
- myWin32API.SetForegroundWindow(this.appSubWinHandle);
- myWin32API.SetFocus(this.appSubWinHandle);
- //System.Threading.Thread.Sleep(100);
- System.Windows.Forms.SendKeys.SendWait("{ENTER}"); //发送ESC键
- //System.Windows.Forms.SendKeys.Send("{ESC}"); //发送ESC键
- //System.Threading.Thread.Sleep(100);
- }
- }
- #region
- //IntPtr ip1 = myWin32API.GetActiveWindow();
- //IntPtr ip2 = myWin32API.GetForegroundWindow();
- //IntPtr ip3 = myWin32API.GetFocus();
- //myWin32API.SetFocus(this.appSubWinHandle);
- //System.Windows.Forms.SendKeys.Send("a"); //发送abcd
- //System.Windows.Forms.SendKeys.Send("{ESC}"); //发送ESC键
- //System.Windows.Forms.SendKeys.Send("{ENTER}"); //发送回车键
- //SendKeys.Send("{ENTER}");
- //END {END}
- //ENTER {ENTER} 或 ~
- //ESC {ESC}
- #endregion
- }
- #region 设置或获取execel.exe应用程序的其他显示式样
- /// <summary>
- /// 测试学习用
- /// </summary>
- /// <returns></returns>
- public bool AppExcel_SelfCheck()
- {
- try
- {
- int x1 = GetCommandBars_Count();
- int X2 = GetMenuBars_Count();
- this.GetApp_ElseProperty();
- this.SetCell_Value(1, 1, "测试值");
- string s = (string)GetCell_Value(1, 1);
- if (s != null) { MessageBox.Show(s); }
- this.SetRangeArray_FontProperty_EG();
- string ss = GetRangeArray_FormatStyle("A1", "B5");
- if (ss != null) { MessageBox.Show(ss); }
- this.GetMenuBars_SerialNumber();
- this.SetSheet_hiddenSheet(2, false);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("App自检有误!" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 获取m_objApp 的 //Count //Name //Version
- /// </summary>
- public void GetApp_ElseProperty()
- {
- //*****************************
- //获取同一个excel进程中,打开的窗口数量总数
- object wbCount = m_objBooks.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, m_objBooks, null);
- Object oName = m_objApp.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, m_objApp, null);
- Object oVersion = m_objApp.GetType().InvokeMember("Version", BindingFlags.GetProperty, null, m_objApp, new object[0]);
- }
- /// <summary>
- /// 返回“数据输入”模式
- /// 处于“数据输入”模式时,仅可在当前选定区域的未锁定单元格中输入数据。Long 类型,可读写。
- /// </summary>
- /// <returns></returns>
- public object GetApp_DataEntryMode()
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- object oAppDataEntryMode = m_objApp.GetType().InvokeMember("DataEntryMode", BindingFlags.GetProperty, null, m_objApp, null); //ok
- return oAppDataEntryMode;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return null;
- }
- }
- /// <summary>
- /// 设置“数据输入”模式
- /// 处于“数据输入”模式时,仅可在当前选定区域的未锁定单元格中输入数据。Long 类型,可读写。
- /// </summary>
- /// <param name="_bStyle"></param>
- /// <returns></returns>
- public bool SetApp_DataEntryMode(int _bStyle)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- object[] m_Parameters_set = new Object[1] { _bStyle };
- m_objApp.GetType().InvokeMember("DataEntryMode", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 获取激活的ActiveWindow对象
- /// </summary>
- /// <returns></returns>
- public object GetApp_ActiveWindow()
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- //选择当前激活的的Window
- object OActiveWindow = m_objApp.GetType().InvokeMember("ActiveWindow", BindingFlags.GetProperty, null, m_objApp, null); //ok
- return OActiveWindow;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return null;
- }
- }
- /// <summary>
- /// 获取激活的ActiveSheet对象
- /// </summary>
- /// <returns></returns>
- public object GetApp_ActiveSheet()
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- //选择当前激活的的Sheet
- object OActiveSheet = m_objApp.GetType().InvokeMember("ActiveSheet", BindingFlags.GetProperty, null, m_objApp, null); //ok
- return OActiveSheet;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return null;
- }
- }
- /// <summary>
- /// 获取激活的ActiveCell对象
- /// </summary>
- /// <returns></returns>
- public object GetApp_ActiveCell()
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- //选择当前激活的的Sheet
- object OActiveCell = m_objApp.GetType().InvokeMember("ActiveCell", BindingFlags.GetProperty, null, m_objApp, null); //ok
- return OActiveCell;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return null;
- }
- }
- /// <summary>
- /// 显示excel程序的界面
- /// </summary>
- /// <param name="_objApp"></param>
- /// <param name="_bVisibleAppForm"></param>
- private void SetApp_Visible(object _objApp, bool _bVisibleAppForm)
- {
- if (m_objApp == null) { return; }
- ////Return control of Excel to the user.
- //object[] m_Parameters_VisibleAppForm = new Object[1] { true };
- object[] m_Parameters_VisibleAppForm = new Object[1] { _bVisibleAppForm };
- _objApp.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, _objApp, m_Parameters_VisibleAppForm);
- ////单步调试不能使用以下该句,否则出错
- //m_objApp.GetType().InvokeMember("UserControl", BindingFlags.SetProperty, null, m_objApp, m_Parameters_VisibleAppForm);
- }
- /// <summary>
- /// 设置窗口的显示模式
- /// </summary>
- /// <param name="_bStyle"> // 1=xlNormal=正常显示 // 2=xlMinimized=最小化显示 // 3=xlMaximized=最大化显示 </param>
- /// <returns></returns>
- public bool SetApp_ExcelWindowState(int _bStyle)
- {
- if (m_objApp == null) { return false; }
- //参数
- // 1=xlNormal=正常显示 // 2=xlMinimized=最小化显示 // 3=xlMaximized=最大化显示
- try
- {
- object[] m_Parameters_set = new Object[1] { _bStyle };
- m_objApp.GetType().InvokeMember("Windowstate", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 显示excel底部状态栏
- /// </summary>
- /// <param name="_bEnabled">true=显示,false=隐藏 (默认 false)</param>
- /// <returns></returns>
- public bool SetApp_DisplayStatusBar(bool _bEnabled)
- {
- if (m_objApp == null) { return false; }
- //m_objExcel.DisplayStatusBar = true; //默认 false 显示excel底部状态栏
- //m_objExcel.DisplayFormulaBar = false; //默认 true true = 显示录入状态栏,false = 不显示录入状态栏
- //m_objExcel.DisplayAlerts = false; //默认 true =在必要时将在代码运行期间显示警告消息。设置为 False 可跳过警告并选择默认值。
- ////当 DisplayAlerts 设置为 False 时,在关闭工作簿前 Excel 不会提示您保存,这样可能会导致丢失数据。
- //m_objExcel.DisplayFullScreen = false; //默认 false
- try
- {
- object[] m_Parameters_set_false = new Object[1] { _bEnabled };
- //object[] m_Parameters_set_true = new Object[1] { true };
- m_objApp.GetType().InvokeMember("DisplayStatusBar", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set_false);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 显示录入状态栏
- /// </summary>
- /// <param name="_bEnabled">true=显示,false=隐藏 (默认 true)</param>
- /// <returns></returns>
- public bool SetApp_DisplayFormulaBar(bool _bEnabled)
- {
- if (m_objApp == null) { return false; }
- //m_objExcel.DisplayStatusBar = true; //默认 false 显示excel底部状态栏
- //m_objExcel.DisplayFormulaBar = false; //默认 true true = 显示录入状态栏,false = 不显示录入状态栏
- //m_objExcel.DisplayAlerts = false; //默认 true =在必要时将在代码运行期间显示警告消息。设置为 False 可跳过警告并选择默认值。
- ////当 DisplayAlerts 设置为 False 时,在关闭工作簿前 Excel 不会提示您保存,这样可能会导致丢失数据。
- //m_objExcel.DisplayFullScreen = false; //默认 false
- try
- {
- object[] m_Parameters_set_false = new Object[1] { _bEnabled };
- //object[] m_Parameters_set_true = new Object[1] { true };
- m_objApp.GetType().InvokeMember("DisplayFormulaBar", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set_false);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// true =在必要时将在代码运行期间显示警告消息。设置为 False 可跳过警告并选择默认值
- /// 当 DisplayAlerts 设置为 False 时,在关闭工作簿前 Excel 不会提示您保存,这样可能会导致丢失数据。
- /// </summary>
- /// <param name="_bEnabled">true=显示,false=隐藏 (默认 true)</param>
- /// <returns></returns>
- public bool SetApp_DisplayAlerts(bool _bEnabled)
- {
- if (m_objApp == null) { return false; }
- //m_objExcel.DisplayStatusBar = true; //默认 false 显示excel底部状态栏
- //m_objExcel.DisplayFormulaBar = false; //默认 true true = 显示录入状态栏,false = 不显示录入状态栏
- //m_objExcel.DisplayAlerts = false; //默认 true =在必要时将在代码运行期间显示警告消息。设置为 False 可跳过警告并选择默认值。
- ////当 DisplayAlerts 设置为 False 时,在关闭工作簿前 Excel 不会提示您保存,这样可能会导致丢失数据。
- //m_objExcel.DisplayFullScreen = false; //默认 false
- try
- {
- object[] m_Parameters_set_false = new Object[1] { _bEnabled };
- //object[] m_Parameters_set_true = new Object[1] { true };
- m_objApp.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set_false);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// true =全屏 false=不全屏 (默认 false)
- /// </summary>
- /// <param name="_bEnabled">true =全屏 false=不全屏 (默认 false)</param>
- /// <returns></returns>
- public bool SetApp_DisplayFullScreen(bool _bEnabled)
- {
- if (m_objApp == null) { return false; }
- //m_objExcel.DisplayStatusBar = true; //默认 false 显示excel底部状态栏
- //m_objExcel.DisplayFormulaBar = false; //默认 true true = 显示录入状态栏,false = 不显示录入状态栏
- //m_objExcel.DisplayAlerts = false; //默认 true =在必要时将在代码运行期间显示警告消息。设置为 False 可跳过警告并选择默认值。
- ////当 DisplayAlerts 设置为 False 时,在关闭工作簿前 Excel 不会提示您保存,这样可能会导致丢失数据。
- //m_objExcel.DisplayFullScreen = false; //默认 false
- try
- {
- object[] m_Parameters_set_false = new Object[1] { _bEnabled };
- //object[] m_Parameters_set_true = new Object[1] { true };
- m_objApp.GetType().InvokeMember("DisplayFullScreen", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set_false);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 获取excel.exe的准备状态
- /// </summary>
- /// <returns></returns>
- public bool GetApp_Ready()
- {
- if (m_objApp == null) { return false; }
- try
- {
- bool bAppReady = (bool)m_objApp.GetType().InvokeMember("Ready", BindingFlags.GetProperty, null, m_objApp, null);
- return bAppReady;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 获取 用户通过键盘和鼠标与Excel之间的交互的状态 true =可以交互 false=不能交互 (默认 true)
- /// </summary>
- /// <returns></returns>
- public bool GetApp_Interactive()
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- bool bInteractive = (bool)m_objApp.GetType().InvokeMember("Interactive", BindingFlags.GetProperty, null, m_objApp, null);
- return bInteractive;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 设置用户通过键盘和鼠标与Excel之间的交互 true =可以交互 false=不能交互 (默认 true)
- /// </summary>
- /// <param name="_bEnabled">true =可以交互 false=不能交互 (默认 true)</param>
- /// <returns></returns>
- public bool SetApp_Interactive(bool _bEnabled)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- object[] m_Parameters_set_false = new Object[1] { _bEnabled };
- //object[] m_Parameters_set_true = new Object[1] { true };
- m_objApp.GetType().InvokeMember("Interactive", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set_false);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 是否显示 禁止"键入需要帮助的问题 DisableAskAQuestionDropdown"
- /// </summary>
- /// <param name="_bDisable"></param>
- /// <returns></returns>
- public bool SetApp_DisableAskAQuestionDropdown(bool _bDisable)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, null);
- try
- {
- m_objApp.GetType().InvokeMember("DisableAskAQuestionDropdown", BindingFlags.SetProperty, null, objCommandBars, new Object[1] { _bDisable });
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return false;
- }
- }
- /// <summary>
- /// 是否显示 禁止“用户自己定义菜单” DisableCustomize
- /// </summary>
- /// <param name="_bDisable"></param>
- /// <returns></returns>
- public bool SetApp_DisableCustomize(bool _bDisable) //
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, null);
- try
- {
- m_objApp.GetType().InvokeMember("DisableCustomize", BindingFlags.SetProperty, null, objCommandBars, new Object[1] { true });
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return false;
- }
- }
- /// <summary>
- /// 显示行号列标
- /// </summary>
- /// <param name="_bVisible">是否显示,false = 禁止显示</param>
- /// <returns>是否成功</returns>
- public bool SetApp_Display_DisplayHeadings(bool _bVisible)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- object[] m_Parameters_set_false = new Object[1] { _bVisible };
- //选择当前激活的
- object OActiveWindow = m_objApp.GetType().InvokeMember("ActiveWindow", BindingFlags.GetProperty, null, m_objApp, null); //ok
- m_objApp.GetType().InvokeMember("DisplayHeadings", BindingFlags.SetProperty, null, OActiveWindow, m_Parameters_set_false); //ok
- //object oActivatorSheet = m_objSheets.GetType().InvokeMember("ActiveSheet", BindingFlags.GetProperty, null, m_objSheets, null); //错误
- //m_objApp.GetType().InvokeMember("DisplayHeadings", BindingFlags.SetProperty, null, oActivatorSheet, m_Parameters_set_false);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// .获取:直接在单元格中进行编辑的能力。如果为 False,则只能在公式栏内编辑单元格
- /// </summary>
- /// <returns></returns>
- public bool GetApp_EditDirectlyInCell()
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- object XX = m_objApp.GetType().InvokeMember("EditDirectlyInCell ", BindingFlags.GetProperty, null, m_objApp, null);
- return (bool)XX;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 设置:直接在单元格中进行编辑的能力。如果为 False,则只能在公式栏内编辑单元格
- /// </summary>
- /// <param name="_bEnabled"></param>
- /// <returns></returns>
- public bool SetApp_EditDirectlyInCell(bool _bEnabled)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- object[] m_Parameters_set_false = new Object[1] { _bEnabled };
- //object[] m_Parameters_set_true = new Object[1] { true };
- m_objApp.GetType().InvokeMember("EditDirectlyInCell ", BindingFlags.SetProperty, null, m_objApp, m_Parameters_set_false);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 待用
- /// </summary>
- /// <param name="target"></param>
- /// <param name="name"></param>
- /// <param name="args"></param>
- /// <returns></returns>
- internal static object SetApp_PropertyInternational(object target, string name, params object[] args)
- {
- return target.GetType().InvokeMember(name,
- System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty |
- System.Reflection.BindingFlags.Public,
- null, target, args, new System.Globalization.CultureInfo(1033));
- }
- /// <summary>
- /// 待用
- /// </summary>
- /// <param name="target"></param>
- /// <param name="name"></param>
- /// <param name="args"></param>
- /// <returns></returns>
- internal static object GetApp_PropertyInternational(object target, string name, params object[] args)
- {
- return target.GetType().InvokeMember(name,
- System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty |
- System.Reflection.BindingFlags.Public,
- null, target, args, new System.Globalization.CultureInfo(1033));
- }
- #endregion
- #region 设置 菜单和命令的显示式样
- /// <summary>
- /// 得到CommandBars的总数
- /// </summary>
- /// <returns>CommandBars的总数</returns>
- public int GetCommandBars_Count()
- {
- if (m_objApp == null) { return 0; }
- object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, null); //Count
- try
- {
- int CommandBarsCount = (int)m_objApp.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, objCommandBars, null); //Count
- object[] m_Parameters_set = new Object[1] { false };
- //m_objApp.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return CommandBarsCount;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return 0;
- }
- }
- /// <summary>
- /// 得到MenuBars的总数
- /// </summary>
- /// <returns>MenuBars的总数</returns>
- public int GetMenuBars_Count()
- {
- if (m_objApp == null) { return 0; }
- object objMenuBars = m_objApp.GetType().InvokeMember("MenuBars", BindingFlags.GetProperty, null, m_objApp, null); //Count
- try
- {
- int CommandBarsCount = (int)m_objApp.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, objMenuBars, null); //Count
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objMenuBars);
- GC.GetTotalMemory(true);
- return CommandBarsCount;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误!错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objMenuBars);
- GC.GetTotalMemory(true);
- return 0;
- }
- }
- /// <summary>
- /// 是否禁止 显示Worksheet Menu Bar 系统菜单
- /// </summary>
- /// <param name="_bEnabled"></param>
- /// <returns></returns>
- public bool SetMenuBars_SystemMenuBar_Enabled(bool _bEnabled) //
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- object[] m_Parameters_Get = new Object[1] { "Worksheet Menu Bar" };
- object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, m_Parameters_Get);
- try
- {
- object X1 = objCommandBars.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, objCommandBars, null); //可以正确执行
- object X2 = objCommandBars.GetType().InvokeMember("Visible", BindingFlags.GetProperty, null, objCommandBars, null); //可以正确执行
- object X3 = objCommandBars.GetType().InvokeMember("Enabled", BindingFlags.GetProperty, null, objCommandBars, null); //可以正确执行
- //object X4 = m_objApp.GetType().InvokeMember("Caption", BindingFlags.GetProperty, null, se.Current, null); //不可以正确执行
- //Enabled //Visible
- object[] m_Parameters_set = new Object[1] { _bEnabled };
- objCommandBars.GetType().InvokeMember("Enabled", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return false;
- }
- }
- /// <summary>
- /// 是否显示 显示Worksheet Menu Bar 系统菜单
- /// </summary>
- /// <param name="_bEnabled"></param>
- /// <returns></returns>
- public bool SetMenuBars_SystemMenuBar_Visible(bool _bEnabled) //
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- object[] m_Parameters_Get = new Object[1] { "Worksheet Menu Bar" };
- object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, m_Parameters_Get);
- try
- {
- object X1 = objCommandBars.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, objCommandBars, null); //可以正确执行
- object X2 = objCommandBars.GetType().InvokeMember("Visible", BindingFlags.GetProperty, null, objCommandBars, null); //可以正确执行
- object X3 = objCommandBars.GetType().InvokeMember("Enabled", BindingFlags.GetProperty, null, objCommandBars, null); //可以正确执行
- //object X4 = m_objApp.GetType().InvokeMember("Caption", BindingFlags.GetProperty, null, se.Current, null); //不可以正确执行
- //Enabled //Visible
- object[] m_Parameters_set = new Object[1] { _bEnabled };
- objCommandBars.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return false;
- }
- }
- /// <summary>
- /// 是否禁止 点击单元格的右健弹出的浮动菜单 disable the Cell menu (menu when you right click on a cell)
- /// </summary>
- /// <param name="_bEnabled"></param>
- /// <returns></returns>
- public bool SetCommandBar_Cell_Enabled(bool _bEnabled) //
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- object[] m_Parameters_Get = new Object[1] { "Cell" };
- object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, m_Parameters_Get);
- try
- {
- object[] m_Parameters_set = new Object[1] { _bEnabled };
- objCommandBars.GetType().InvokeMember("Enabled", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return false;
- }
- }
- /// <summary>
- ///指定CommandBars名字 来设置其禁止与否 其中针对是否禁用 Worksheet Menu Bar 只能选择Enabled",不能Visible
- /// </summary>
- /// <param name="_strCommandBarsName">先得确定是否有CommandBars 的名字, 如 "Worksheet Menu Bar" "Standard" "Cell" </param>
- /// <param name="_bEnabled">是否禁用</param>
- /// <returns></returns>
- public bool SetCommandBarName_Enabled(string _strCommandBarsName, bool _bEnabled)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- object[] m_Parameters_Get = new Object[1] { _strCommandBarsName };
- object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, m_Parameters_Get);
- try
- {
- object[] m_Parameters_set = new Object[1] { _bEnabled };
- objCommandBars.GetType().InvokeMember("Enabled", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return false;
- }
- }
- /// <summary>
- /// 指定CommandBars名字 来设置其显示与否 其中针对是否显示 Worksheet Menu Bar 只能选择Enabled",不能Visible
- /// </summary>
- /// <param name="_strCommandBarsName">先得确定是否有CommandBars的名字 如"Standard" "Formatting" "Envelope" "Task Pane" </param>
- /// <param name="_bVisible"></param>
- /// <returns></returns>
- public bool SetCommandBarName_Visible(string _strCommandBarsName, bool _bVisible)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- object[] m_Parameters_Get = new Object[1] { _strCommandBarsName };
- object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, m_Parameters_Get);
- try
- {
- if ((bool)objCommandBars.GetType().InvokeMember("Visible", BindingFlags.GetProperty, null, objCommandBars, null))
- {
- object[] m_Parameters_set = new Object[1] { _bVisible };
- objCommandBars.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set);
- }
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return false;
- }
- }
- /// <summary>
- /// 设置excel.exe应用程序的系统下拉菜单的Enabled 和Visible : true=(Enabled + Visible),false= (禁止 + 不可见)
- /// </summary>
- /// <param name="_bEnabled">true=(Enabled + Visible),false= (禁止 + 不可见)</param>
- /// <returns></returns>
- public void SetApp_ExcelSystemMenu_xiala(bool _bEnabled)
- {
- this.SetCommandBarName_Enabled("Worksheet Menu Bar", _bEnabled); ; //excel的系统主菜单
- this.SetCommandBarName_Visible("Worksheet Menu Bar", _bEnabled); ; //excel的系统主菜单
- }
- /// <summary>
- /// 设置excel.exe应用程序的标准命令工具栏(Standard)的Enabled 和Visible : true=(Enabled + Visible),false= (禁止 + 不可见)
- /// </summary>
- /// <param name="_bEnabled">true=(Enabled + Visible),false= (禁止 + 不可见)</param>
- /// <returns></returns>
- public void SetApp_ExcelSystemMenu_Standard(bool _bEnabled)
- {
- this.SetCommandBarName_Enabled("Standard", _bEnabled); ; //excel的系统主菜单
- this.SetCommandBarName_Visible("Standard", _bEnabled); ; //excel的系统主菜单
- }
- /// <summary>
- /// 设置excel.exe应用程序的标准格式化工具栏(Standard)的Enabled 和Visible : true=(Enabled + Visible),false= (禁止 + 不可见)
- /// </summary>
- /// <param name="_bEnabled">true=(Enabled + Visible),false= (禁止 + 不可见)</param>
- /// <returns></returns>
- public void SetApp_ExcelSystemMenu_Formatting(bool _bEnabled)
- {
- this.SetCommandBarName_Enabled("Formatting", _bEnabled); ; //excel的系统主菜单
- this.SetCommandBarName_Visible("Formatting", _bEnabled); ; //excel的系统主菜单
- }
- /// <summary>
- /// 指定CommandBars名字的ID号 来设置其显示与否 其中针对是否显示 如"文件"的ID为"30002" ,该方法尚在测试,不能正常使用
- /// </summary>
- /// <param name="_nCommandBarID">如"文件"的ID为"30002"</param>
- /// <returns></returns>
- public bool SetCommandBarID_Visible(int _nCommandBarID) //指定ID
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- //Standard //Menu Bar // Standard // Formatting // Ink // Envelope // Online Meeting // Print Preview // System // Tables // Task Pane
- object[] m_Parameters_Get = new Object[1] { "Worksheet Menu Bar" }; //{ "Worksheet Menu Bar" }; //Standard
- object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, m_Parameters_Get); //OK
- m_Parameters_Get = new Object[1] { 30002 }; //可以这样定义,但后面不知道怎样调用方法
- object objCommandBarControl = objCommandBars.GetType().InvokeMember("Controls", BindingFlags.GetProperty, null, objCommandBars, null); //OK
- object[] m_Parameters_set = new Object[1] { false }; ////Enabled //Visible
- objCommandBars.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, objCommandBars, m_Parameters_set); //???
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBarControl);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 枚举CommandBars的名字 再禁止其使能 全部Enabled = false;
- /// </summary>
- /// <returns></returns>
- public bool SetCommandBars_IEnumeratorCommandBarsName() //App_SetAppCommandBarsVisible //Standard //Menu Bar
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- object objCommandBars = m_objApp.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, m_objApp, null);
- object objCommandBarsGetEnumerator = objCommandBars.GetType().InvokeMember("GetEnumerator", BindingFlags.InvokeMethod, null, objCommandBars, null);
- string strCommandBarsName = "";
- System.Collections.IEnumerator se = (System.Collections.IEnumerator)objCommandBarsGetEnumerator;
- while (se.MoveNext())
- {
- object X1 = objCommandBars.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, se.Current, null); //可以正确执行
- object X2 = objCommandBars.GetType().InvokeMember("Visible", BindingFlags.GetProperty, null, se.Current, null); //可以正确执行
- object X3 = objCommandBars.GetType().InvokeMember("Enabled", BindingFlags.GetProperty, null, se.Current, null); //可以正确执行
- //object X4 = m_objApp.GetType().InvokeMember("Caption", BindingFlags.GetProperty, null, se.Current, null); //不可以正确执行
- strCommandBarsName += (string)X1 + " Visible===" + X2.ToString() + " Enabled===" + X3.ToString() + "\r\n";
- if ((bool)X2)
- {
- if ((bool)X3)
- {
- SetCommandBarName_Enabled(X1.ToString(), false); //禁止
- }
- }
- }
- //MessageBox.Show(strCommandBarsName); //调试用,察看CommandBars的名字和状态
- //SuperTools.FileTools.StringToSaveLogFile(strCommandBarsName, false);
- objCommandBarsGetEnumerator = null;
- System.Runtime.InteropServices.Marshal.ReleaseComObject(objCommandBars);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 枚举MenuBars
- /// </summary>
- /// <returns></returns>
- public bool GetMenuBars_SerialNumber() //App_SetAppCommandBarsVisible //Standard //Menu Bar
- {
- if (m_objApp == null) { return false; }
- int x = GetMenuBars_Count();
- try
- {
- //object[] m_Parameters_Get = new Object[1] { 30002 };
- object objMenuBars = m_objApp.GetType().InvokeMember("MenuBars", BindingFlags.GetProperty, null, m_objApp, null); // GetEnumerator
- object objMenuBarsGetEnumerator = m_objApp.GetType().InvokeMember("GetEnumerator", BindingFlags.GetProperty, null, objMenuBars, null);
- //object objMenuBars11 = m_objApp.GetType().InvokeMember("Worksheet Menu Bar", BindingFlags.GetProperty, null, objMenuBars, null);
- string strCommandBarsName = "";
- System.Collections.IEnumerator se = (System.Collections.IEnumerator)objMenuBarsGetEnumerator;
- int i = 0;
- while (se.MoveNext())
- {
- i = i + 1;
- object X1 = "菜单" + i.ToString(); // se.Current.GetType().InvokeMember("ID", BindingFlags.GetProperty, null, se.Current, null); //不能正确执行
- //object X2 = m_objApp.GetType().InvokeMember("ID", BindingFlags.GetProperty, null, se.Current, null); //不能正确执行
- strCommandBarsName += X1.ToString() + "\r\n";
- //object[] m_Parameters_set_1 = new Object[1] { false }; //Visible //Enabled
- //m_objApp.GetType().InvokeMember("Visible", BindingFlags.SetPropert, null, se.Current, m_Parameters_set_1); //???
- }
- MessageBox.Show("枚举MenuBars如下:\r\n" + strCommandBarsName);
- //System.Runtime.InteropServices.Marshal.ReleaseComObject(objMenuBarsGetEnumerator);
- objMenuBarsGetEnumerator = null;
- //System.Runtime.InteropServices.Marshal.ReleaseComObject(objMenuBars);
- //GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- #endregion
- #region sheet 操作
- /// <summary>
- /// 获取sheets的总数
- /// </summary>
- /// <returns>sheets的总数</returns>
- public int GetSheet_SheetsCount()
- {
- if (m_objApp == null) { return 0; }
- if (m_objSheet == null) { return 0; }
- this.SetApp_Exit_EditMode();
- try
- {
- int SheetsCount = (int)m_objSheets.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, m_objSheets, null);
- return SheetsCount;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误!错误原因:" + ex.Message);
- return 0;
- }
- }
- /// <summary>
- /// 获取激活的sheet对象
- /// </summary>
- /// <returns></returns>
- public object GetSheet_Active_Sheet()
- {
- if (m_objApp == null) { return null; }
- if (m_objSheet == null) { return null; }
- this.SetApp_Exit_EditMode();
- try
- {
- //选择当前激活的的Window
- object OActiveWindow = m_objApp.GetType().InvokeMember("ActiveWindow", BindingFlags.GetProperty, null, m_objApp, null); //ok
- //选择当前激活的的Sheet
- object OActiveSheet = m_objApp.GetType().InvokeMember("ActiveSheet", BindingFlags.GetProperty, null, OActiveWindow, null); //ok
- return OActiveSheet;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return null;
- }
- }
- /// <summary>
- /// 获取激活的sheet 的sheet 的名字
- /// </summary>
- /// <returns></returns>
- public string GetSheet_ActiveSheetName()
- {
- if (m_objApp == null) { return string.Empty; }
- if (m_objSheet == null) { return string.Empty; }
- this.SetApp_Exit_EditMode();
- object m_objActiveSheet = m_objApp.GetType().InvokeMember("ActiveSheet", BindingFlags.GetProperty, null, m_objApp, null);
- if (m_objActiveSheet == null) { return ""; }
- string SheetName;
- try
- {
- SheetName = (string)m_objActiveSheet.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, m_objActiveSheet, null);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objActiveSheet);
- GC.GetTotalMemory(true);
- return SheetName;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objActiveSheet);
- GC.GetTotalMemory(true);
- return string.Empty;
- }
- }
- /// <summary>
- /// 获取制定sheet的名字
- /// </summary>
- /// <param name="iNoSheet">sheet序号,从1开始</param>
- /// <returns>sheet的名字</returns>
- public string GetSheet_SheetName(int iNoSheet) //GetSheet_ActiveSheetName
- {
- if (m_objSheets == null) { return string.Empty; }
- int SheetsCount = GetSheet_SheetsCount();
- if (iNoSheet > SheetsCount || iNoSheet < 1)
- {
- return string.Empty;
- }
- object[] m_Parameters_set = new Object[1] { iNoSheet }; //第一个sheet:sheet1
- object m_objSheet_1 = m_objSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, m_objSheets, m_Parameters_set);
- string SheetName;
- try
- {
- SheetName = (string)m_objSheet_1.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, m_objSheet_1, null);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
- GC.GetTotalMemory(true);
- return SheetName;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
- GC.GetTotalMemory(true);
- return string.Empty;
- }
- }
- /// <summary>
- /// 改变Sheet的名字
- /// </summary>
- /// <param name="iNoSheet">Sheet序号,从1开始</param>
- /// <param name="_SheetName">新名字</param>
- /// <returns>是否正确返回</returns>
- public bool SetSheet_ChangSheetName(int iNoSheet, string _SheetName) //
- {
- if (m_objSheets == null) { return false; }
- int SheetsCount = GetSheet_SheetsCount();
- if (iNoSheet > SheetsCount || iNoSheet < 1)
- {
- return false;
- }
- object[] m_Parameters_set = new Object[1] { iNoSheet }; //第一个sheet:sheet1
- object m_objSheet_1 = m_objSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, m_objSheets, m_Parameters_set);
- try
- {
- m_Parameters_set = new Object[1] { _SheetName };
- m_objSheet_1.GetType().InvokeMember("Name", BindingFlags.SetProperty, null, m_objSheet_1, m_Parameters_set);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
- GC.GetTotalMemory(true);
- return false;
- }
- }
- /// <summary>
- /// 根据sheet的表格序号,改变当前工作sheet
- /// </summary>
- /// <param name="iNoSheet">待激活的sheet序号,从1开始</param>
- public bool SetSheet_ChangeActivateSheet(int iNoSheet)
- {
- if (m_objSheets == null) { return false; }
- int SheetsCount = GetSheet_SheetsCount();
- if (iNoSheet > SheetsCount || iNoSheet < 1)
- {
- return false;
- }
- object[] m_Parameters_ActivatorSheet = new Object[1] { iNoSheet }; //第一个sheet:sheet1
- object m_objSheet_1 = m_objSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, m_objSheets, m_Parameters_ActivatorSheet);
- try
- {
- m_objSheet_1.GetType().InvokeMember("Activate", BindingFlags.InvokeMethod, null, m_objSheet_1, null);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("激活sheet序号错误!错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
- GC.GetTotalMemory(true);
- return false;
- }
- }
- /// <summary>
- /// 只显示sheet1,其余的sheet全部隐藏
- /// </summary>
- /// <param name="bVisible">false = 显示,true =隐藏 </param>
- /// <returns> </returns>
- public bool SetSheet_DisplaySheet1_hiddenElseAllSheets(bool bVisible)
- {
- if (m_objSheets == null) { return false; }
- try
- {
- int SheetsCount = GetSheet_SheetsCount();
- for (int i = 2; i <= SheetsCount; i++) //保留第一个Sheet显示
- {
- this.SetSheet_hiddenSheet(i, bVisible);
- }
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 是否显示隐藏 sheet
- /// </summary>
- /// <param name="iNoSheet">sheet的序号</param>
- /// <param name="_bVisible">false = 显示,true =隐藏 </param>
- /// <returns></returns>
- public bool SetSheet_hiddenSheet(int iNoSheet, bool _bVisible)
- {
- if (m_objSheets == null) { return false; }
- int SheetsCount = GetSheet_SheetsCount();
- if (iNoSheet > SheetsCount || iNoSheet < 1)
- {
- return false;
- }
- object[] m_Parameters_ActivatorSheet = new Object[1] { iNoSheet }; //第一个sheet:sheet1
- object m_objSheet_1 = m_objSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, m_objSheets, m_Parameters_ActivatorSheet);
- try
- {
- object[] m_Parameters_Set = new Object[1];
- if (_bVisible)
- {
- m_Parameters_Set[0] = 2; //隐藏
- }
- else
- {
- m_Parameters_Set[0] = 1; //取消
- }
- m_objSheet_1.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, m_objSheet_1, m_Parameters_Set);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet_1);
- GC.GetTotalMemory(true);
- return false;
- }
- }
- #endregion
- #region 单元格的读写操作
- /// <summary>
- /// 内部使用,获取激活单元格的属性
- /// </summary>
- /// <param name="_strPropertyName">激活单元格的名字</param>
- /// <returns>激活单元格的值</returns>
- internal object GetCell_ActiveCell_Property(string _strPropertyName)
- {
- if (m_objApp == null) { return null; }
- if (m_objSheet == null) { return null; }
- this.SetApp_Exit_EditMode();
- object m_objActiveCell = m_objApp.GetType().InvokeMember("ActiveCell", BindingFlags.GetProperty, null, m_objApp, null);
- if (m_objActiveCell == null) { return 0; }
- try
- {
- object oPropertyValue = (int)m_objActiveCell.GetType().InvokeMember(_strPropertyName, BindingFlags.GetProperty, null, m_objActiveCell, null);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objActiveCell);
- GC.GetTotalMemory(true);
- return oPropertyValue;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误原因:" + ex.Message);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objActiveCell);
- GC.GetTotalMemory(true);
- return null;
- }
- }
- /// <summary>
- /// 得到激活单元格的列的序号,从1开始
- /// </summary>
- /// <returns></returns>
- public int GetCell_ActiveCell_ColumnNumber() // object m_obj
- {
- int nColumnNumber = (int)this.GetCell_ActiveCell_Property("Column");
- return nColumnNumber;
- }
- /// <summary>
- /// 得到激活单元格的列名
- /// </summary>
- /// <returns></returns>
- public string GetCell_ActiveCell_ColumnName()
- {
- int n1 = this.GetCell_ActiveCell_ColumnNumber();
- string str1 = SuperTools.UC_EmbedExcelIntoWinFormNoDLL.Tool_NtoL(n1);
- return str1;
- }
- /// <summary>
- /// 得到激活单元格的行的序号,从1开始
- /// </summary>
- /// <returns></returns>
- public int GetCell_ActiveCell_RowNumber()
- {
- int nRowNumber = (int)GetCell_ActiveCell_Property("Row");
- return nRowNumber;
- }
- /// <summary>
- /// 获取单元格的位置名字,如得到"B5"
- /// </summary>
- /// <returns></returns>
- public string GetCell_ActiveCell_Name()
- {
- string strActiveCell_RowName = this.GetCell_ActiveCell_RowNumber().ToString();
- string strActiveCell_ColumnName = this.GetCell_ActiveCell_ColumnName();
- return strActiveCell_ColumnName + strActiveCell_RowName;
- }
- /// <summary>
- /// Range位置,如:"A1"
- /// </summary>
- /// <param name="strRange"></param>
- /// <returns></returns>
- public bool SetCell_ActiveCell(string strRange)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- //object[] Parameters_range = new object[2] { "A1", System.Reflection.Missing.Value };
- //object[] Parameters_range = new object[2] { strRange, System.Reflection.Missing.Value };
- object[] Parameters_range = new object[2];
- Parameters_range[0] = strRange;
- Parameters_range[1] = System.Reflection.Missing.Value;
- object m_objRange = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_range);
- if (m_objRange == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- m_objRange.GetType().InvokeMember("Activate", BindingFlags.InvokeMethod, null, m_objRange, null);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRange);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("写入错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 写Cells单元格的值
- /// </summary>
- /// <param name="x">第x行,Excel的起始列为1</param>
- /// <param name="y">第y列,Excel的起始行为1</param>
- /// <param name="strWriteValue">写入的数值</param>
- /// <returns>bool,是否正确写入</returns>
- public bool SetCell_Value(int x, int y, string strWriteValue)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- object[] Parameters_Cells = new object[2] { x, y }; //第x行,第y列
- object m_objCells = m_objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty, null, m_objSheet, Parameters_Cells);
- if (m_objCells == null)
- {
- Console.WriteLine("出错啦: m_objCells == null,请检查Cells的设置。");
- }
- //向指定单元格填写内容值
- object[] Parameters_WriteValue = new Object[1] { strWriteValue }; //文本值写到excel当中
- m_objCells.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, m_objCells, Parameters_WriteValue);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objCells);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("写入错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 获取Cells单元格的值
- /// </summary>
- /// <param name="x">第x行,Excel的起始列为1</param>
- /// <param name="y">第y列,Excel的起始行为1</param>
- /// <returns>object</returns>
- public object GetCell_Value(int x, int y)
- {
- if (m_objApp == null) { return null; }
- if (m_objSheet == null) { return null; }
- this.SetApp_Exit_EditMode();
- object[] Parameters_Cells = new object[2] { x, y }; //第x行,第y列
- object m_objCells = m_objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, m_objSheet, Parameters_Cells);
- if (m_objCells == null)
- {
- Console.WriteLine("出错啦: Cells == null,请检查Cells的设置。");
- }
- object m_objCellsValue = m_objCells.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, m_objCells, new object[0]);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objCells);
- GC.GetTotalMemory(true);
- return m_objCellsValue;
- }
- /// <summary>
- /// 获取Cells单元格的值 ,并将该单元格的值转化为string的数据类型
- /// </summary>
- /// <param name="x">第x行,Excel的起始列为1</param>
- /// <param name="y">第y列,Excel的起始行为1</param>
- /// <returns>Cells单元格的本文值</returns>
- public string GetCell_Value_toString(int x, int y)
- {
- object ob1 = this.GetCell_Value(x, y);
- if (ob1 != null)
- {
- string ss = ob1.ToString();
- return ss;
- }
- else
- {
- return "";
- }
- }
- /// <summary>
- /// 写Range单元格的值
- /// </summary>
- /// <param name="strRange">Range单元格位置,如"A1"</param>
- /// <param name="strWriteValue"></param>
- /// <returns></returns>
- public bool SetRange_Value(string strRange, string strWriteValue)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- //object[] Parameters_range = new object[2] { "A1", System.Reflection.Missing.Value };
- //object[] Parameters_range = new object[2] { strRange, System.Reflection.Missing.Value };
- object[] Parameters_range = new object[2];
- Parameters_range[0] = strRange;
- Parameters_range[1] = System.Reflection.Missing.Value;
- object m_objRange = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_range);
- if (m_objRange == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- //向指定单元格填写内容值
- object[] Parameters_WriteValue = new Object[1] { strWriteValue }; //文本值写到excel当中
- m_objRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, m_objRange, Parameters_WriteValue);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRange);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("写入错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 获取Range单元格的值
- /// </summary>
- /// <param name="strRange">Range位置,如:"A1"</param>
- /// <returns>object</returns>
- public object GetRange_Value(string strRange)
- {
- if (m_objApp == null) { return null; }
- if (m_objSheet == null) { return null; }
- this.SetApp_Exit_EditMode();
- //object[] Parameters_range = new object[2] { "A1", System.Reflection.Missing.Value };
- object[] Parameters_range = new object[2] { strRange, System.Reflection.Missing.Value };
- object m_objRange = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, m_objSheet, Parameters_range);
- if (m_objRange == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- object m_objRangeValue = m_objRange.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, m_objRange, new object[0]);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRange);
- GC.GetTotalMemory(true);
- return m_objRangeValue;
- }
- /// <summary>
- /// 获取Range单元格的值 ,并将该单元格的值转化为string的数据类型
- /// </summary>
- /// <param name="strRange">Range位置,如:"A1"</param>
- /// <returns>Range单元格的本文值</returns>
- public string GetRange_Value_toString(string strRange)
- {
- object ob1 = GetRange_Value(strRange);
- if (ob1 != null)
- {
- string ss = ob1.ToString();
- return ss;
- }
- else
- {
- return "";
- }
- }
- /// <summary>
- /// 将二维数组 写入 excel
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_Array_Value">写入的二维数组的值,可以是各种数据类型</param>
- /// <returns>bool,是否正确写入</returns>
- public bool SetRangeArray_Value(string _BeginPoint, string _EndPoint, object[,] _Array_Value)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- if (m_objRangeArray == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- //************************
- //得到写入值
- Object[] ParametersArray_WriteValue = new Object[1];
- ParametersArray_WriteValue[0] = _Array_Value; //赋值:数值类型=int
- //******************
- m_objRangeArray.GetType().InvokeMember("Value2", BindingFlags.SetProperty, null, m_objRangeArray, ParametersArray_WriteValue);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("写入错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 将二维数组 写入 excel的一个实例,写入不同的数据类型
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">EndPoint">终止位置 如"B5"</param>
- /// <param name="_myDataType">数据类型,如ypeof(int) typeof(String) typeof(bool) typeof(DateTime) typeof(double) </param>
- /// <returns></returns>
- public bool SetRangeArray_Value_EG(string _BeginPoint, string _EndPoint, System.Type _myDataType)
- {
- try
- {
- //************************
- int BeginPoint_y = System.Convert.ToInt16(_BeginPoint.Substring(1, 1));
- int EndPoint_y = System.Convert.ToInt16(_EndPoint.Substring(1, 1));
- int rows = EndPoint_y - BeginPoint_y + 1;
- //************************
- string strBeginPoint_X = _BeginPoint.Substring(0, 1);
- string strEndPoint_X = _EndPoint.Substring(0, 1);
- int columns = strEndPoint_X[0] - strBeginPoint_X[0] + 1;
- //************************
- Object[,] EG_Array_WriteValue = new object[rows, columns];
- #region 各种数据类型
- switch (_myDataType.Name)
- {
- case "Int32": //typeof(double)
- int[,] Array_int_Value = new int[rows, columns]; //赋值:数值类型=int //typeof(int)
- for (int i = 0; i < rows; i++)
- {
- for (int j = 0; j < columns; j++)
- {
- Array_int_Value[i, j] = i + j;
- }
- }
- Array.Copy(Array_int_Value, EG_Array_WriteValue, rows * columns);
- break;
- case "String": //typeof(string)
- string[,] Array_string_Value = new string[rows, columns]; //赋值:数值类型=string
- for (int i = 0; i < rows; i++)
- {
- for (int j = 0; j < columns; j++)
- {
- Array_string_Value[i, j] = i.ToString() + "<>" + j.ToString();
- }
- }
- Array.Copy(Array_string_Value, EG_Array_WriteValue, rows * columns);
- break;
- case "DateTime":
- DateTime[,] Array_DateTime_Value = new DateTime[rows, columns]; //赋值:数值类型=时间
- for (int i = 0; i < rows; i++)
- {
- for (int j = 0; j < columns; j++)
- {
- Array_DateTime_Value[i, j] = DateTime.Now.Date; //取得当前系统时间
- }
- }
- Array.Copy(Array_DateTime_Value, EG_Array_WriteValue, rows * columns);
- break;
- case "Boolean": //typeof(bool)
- Boolean[,] Array_bool_Value = new Boolean[rows, columns]; //赋值:数值类型=Bool
- for (int i = 0; i < rows; i++)
- {
- for (int j = 0; j < columns; j++)
- {
- Array_bool_Value[i, j] = true;
- }
- }
- Array.Copy(Array_bool_Value, EG_Array_WriteValue, rows * columns);
- break;
- }
- #endregion
- //******************
- SetRangeArray_Value(_BeginPoint, _EndPoint, EG_Array_WriteValue); //调用本类中的App_SetRangeArrayValue方法
- return true; ;
- //******************V
- }
- catch (Exception ex)
- {
- MessageBox.Show("写入二维数组示例错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 读取excel的一个范围到一个二维数组里面, 不同的数据类型
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <returns>object[,]</returns>
- public object[,] GetRangeArray_Value(string _BeginPoint, string _EndPoint)
- {
- if (m_objApp == null) { return null; }
- if (m_objSheet == null) { return null; }
- this.SetApp_Exit_EditMode();
- try
- {
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- if (m_objRangeArray == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- //******************
- object[,] m_objRangeArrayValue = (object[,])m_objRangeArray.GetType().InvokeMember("Value2", BindingFlags.GetProperty, null, m_objRangeArray, new object[0]);
- //object[,] m_objRangeArrayValue = (object[,])m_objRangeArray.GetType().InvokeMember("Value2", BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty, null, m_objRangeArray, new object[0]);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- //******************
- int rows = m_objRangeArrayValue.GetLength(0); //获取m_objRangeArrayValue的行数
- int columns = m_objRangeArrayValue.GetLength(1); //获取m_objRangeArrayValue的列数
- object[,] param = new object[rows, columns]; //转化为起始为0的数组
- Array.Copy(m_objRangeArrayValue, param, rows * columns); //临时结果,学习用
- //******************
- return m_objRangeArrayValue; // public object[,] App_GetRangeArrayValue(string _BeginPoint, string _EndPoint)
- }
- catch (Exception ex)
- {
- MessageBox.Show("读取excel的数组错误!错误原因:" + ex.Message);
- return null;
- }
- }
- /// <summary>
- /// 設定值,指出文字是否會自動縮小以符合可用的栏宽?
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_bEnabled">true=自动适应栏宽,false=不自动适应栏宽(默认= false)</param>
- /// <returns></returns>
- public bool SetRangeArray_ShrinkToFit(string _BeginPoint, string _EndPoint, bool _bEnabled)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- if (m_objRangeArray == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- //************************
- //得到写入值
- Object[] ParametersArray_WriteValue = new Object[1];
- ParametersArray_WriteValue[0] = _bEnabled; //赋值:数值类型=int
- //******************
- m_objRangeArray.GetType().InvokeMember("ShrinkToFit", BindingFlags.SetProperty, null, m_objRangeArray, ParametersArray_WriteValue);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("写入错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 設定指出 NamedRange 控制項是否為鎖定的值。?
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_bEnabled">true=鎖定,false=不鎖定(默认= false)</param>
- /// <returns></returns>
- public bool SetRangeArray_Locked(string _BeginPoint, string _EndPoint, bool _bEnabled)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- if (m_objRangeArray == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- //************************
- //得到写入值
- Object[] ParametersArray_WriteValue = new Object[1];
- ParametersArray_WriteValue[0] = _bEnabled; //赋值:数值类型=int
- //******************
- m_objRangeArray.GetType().InvokeMember("Locked", BindingFlags.SetProperty, null, m_objRangeArray, ParametersArray_WriteValue);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("写入错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 获取 NamedRange 控制項是否為鎖定的值。?
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <returns></returns>
- public bool GetRangeArray_Locked(string _BeginPoint, string _EndPoint)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- if (m_objRangeArray == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- //************************
- Object oLocked = m_objRangeArray.GetType().InvokeMember("Locked", BindingFlags.GetProperty, null, m_objRangeArray, null);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- return (bool)oLocked;
- }
- catch (Exception ex)
- {
- MessageBox.Show("写入错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 读取excel的某一固定列中几行的数据到一个二维数组里面, 不同的数据类型
- /// </summary>
- /// <param name="x_ColumnName">excel列的名字,如"A" "B" "B"</param>
- /// <param name="y1">该列的起始位置</param>
- /// <param name="RowsCount">读取的行数</param>
- /// <returns>System.Collections.ArrayList</returns>
- public System.Collections.ArrayList GetRangeArray_Value_ArrayList(string x_ColumnName, int y1, int RowsCount)
- {
- string BeginPoint = x_ColumnName.ToUpper() + y1.ToString();
- string EndPoint = x_ColumnName.ToUpper() + (y1 + RowsCount - 1).ToString();
- object[,] ValueArray = GetRangeArray_Value(BeginPoint, EndPoint); //调用本类中的方法:App_GetRangeArrayValue
- System.Collections.ArrayList aa = Tools_Array2ArrayList(ValueArray); //调用/调用本类中的静态方法:Tools_Array2ArrayList
- return aa;
- }
- /// <summary>
- /// 读取excel的某一固定行中几列的数据到一个二维数组里面, 不同的数据类型
- /// </summary>
- /// <param name="x_ColumnName_1">excel起始列的名字,如"A" "B" "B"</param>
- /// <param name="x_ColumnName_2">excel终止列的名字,如"A" "B" "B"</param>
- /// <param name="RowsNumber">读取的行的序号</param>
- /// <returns>System.Collections.ArrayList </returns>
- public System.Collections.ArrayList GetRangeArray_Value_ArrayList(string x_ColumnName_1, string x_ColumnName_2, int RowsNumber)
- {
- string BeginPoint = x_ColumnName_1.ToUpper() + RowsNumber.ToString();
- string EndPoint = x_ColumnName_2.ToUpper() + RowsNumber.ToString();
- object[,] ValueArray = GetRangeArray_Value(BeginPoint, EndPoint); //调用本类中的方法:App_GetRangeArrayValue
- System.Collections.ArrayList aa = Tools_Array2ArrayList(ValueArray); //调用/调用本类中的静态方法:Tools_Array2ArrayList
- return aa;
- }
- /// <summary>
- /// 读取excel的某一固定列中几行的数据到一个二维数组里面, 不同的数据类型 转化为string[]
- /// </summary>
- /// <param name="x_ColumnName">excel列的名字,如"A" "B" "B"</param>
- /// <param name="y1">该列的起始位置</param>
- /// <param name="RowsCount">读取的行数</param>
- /// <returns>string[]</returns>
- public string[] GetRangeArray_Value_string(string x_ColumnName, int y1, int RowsCount)
- {
- string BeginPoint = x_ColumnName.ToUpper() + y1.ToString();
- string EndPoint = x_ColumnName.ToUpper() + (y1 + RowsCount - 1).ToString();
- object[,] ValueArray = GetRangeArray_Value(BeginPoint, EndPoint); //调用本类中的方法:App_GetRangeArrayValue
- string[] cc = Tools_ConvertToStringArray(ValueArray);
- return cc;
- }
- /// <summary>
- /// 读取excel的某一固定行中几列的数据到一个二维数组里面, 不同的数据类型 转化为string[]
- /// </summary>
- /// <param name="x_ColumnName_1">excel起始列的名字,如"A" "B" "B"</param>
- /// <param name="x_ColumnName_2">excel终止列的名字,如"A" "B" "B"</param>
- /// <param name="RowsNumber">读取的行的序号</param>
- /// <returns>string[]</returns>
- public string[] GetRangeArray_Value_string(string x_ColumnName_1, string x_ColumnName_2, int RowsNumber)
- {
- string BeginPoint = x_ColumnName_1.ToUpper() + RowsNumber.ToString();
- string EndPoint = x_ColumnName_2.ToUpper() + RowsNumber.ToString();
- object[,] ValueArray = GetRangeArray_Value(BeginPoint, EndPoint); //调用本类中的方法:App_GetRangeArrayValue
- //System.Collections.ArrayList aa = Tools_Array2ArrayList(ValueArray); //调用/调用本类中的静态方法:Tools_Array2ArrayList
- //object[] bb = Tools_ArrayList2Array(aa);
- string[] cc = Tools_ConvertToStringArray(ValueArray);
- return cc;
- }
- /// <summary>
- /// 将object[,]转换为ArrayList
- /// </summary>
- /// <param name="_object_Array_Value"></param>
- /// <returns></returns>
- public static System.Collections.ArrayList Tools_Array2ArrayList(object[,] _object_Array_Value)
- {
- System.Collections.ArrayList myArrayList = new System.Collections.ArrayList();
- System.Collections.IEnumerator se = _object_Array_Value.GetEnumerator();
- while (se.MoveNext())
- {
- myArrayList.Add(se.Current);
- }
- return myArrayList;
- //System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
- // ParaColumns.Add("ID|Int16"); //
- // ParaColumns.Add("日期|DateTime"); // System.DateTime
- // ParaColumns.Add("工资|Decimal"); //System.Decimal
- }
- /// <summary>
- /// 将ArrayList转换为 object[,]
- /// </summary>
- /// <param name="_ArrayList"></param>
- /// <returns></returns>
- public static object[] Tools_ArrayList2Array(System.Collections.ArrayList _ArrayList)
- {
- object[] ValueArray = _ArrayList.ToArray();
- return ValueArray;
- }
- /// <summary>
- /// object[,]转化成为string[]
- /// </summary>
- /// <param name="values"></param>
- /// <returns></returns>
- private static string[] Tools_ConvertToStringArray(object[,] values)
- {
- string[] newArray = new string[values.Length];
- int index = 0;
- for (int i = values.GetLowerBound(0); i <= values.GetUpperBound(0); i++)
- {
- for (int j = values.GetLowerBound(1); j <= values.GetUpperBound(1); j++)
- {
- if (values.GetValue(i, j) == null)
- {
- newArray[index] = "";
- }
- else
- {
- newArray[index] = (string)values.GetValue(i, j).ToString();
- }
- index++;
- }
- }
- return newArray;
- }
- //
- /// <summary>
- /// 判断字符是否
- /// </summary>
- /// <param name="anyString"></param>
- /// <returns></returns>
- public static bool Tools_IsNumeric(string anyString)
- {
- if (anyString == null)
- {
- anyString = "";
- }
- if (anyString.Length > 0)
- {
- double dummyOut = new double();
- System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US", true);
- return Double.TryParse(anyString, System.Globalization.NumberStyles.Any, cultureInfo.NumberFormat, out dummyOut);
- }
- else
- {
- return false;
- }
- }
- /// <summary>
- /// 设置Columns的属性:列最适应宽度
- /// </summary>
- /// <param name="_strColumnsPropertyName">Columns的属性名字</param>
- /// <param name="_Parameters_Set">Columns的属性设置值</param>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <returns></returns>
- internal bool SetRangeArray_RangeProperty_Columns(string _strColumnsPropertyName, object[] _Parameters_Set, string _BeginPoint, string _EndPoint)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- //********************
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- if (m_objRangeArray == null)
- {
- Console.WriteLine("出错啦: m_objRangeArray == null,请检查range的设置。");
- }
- //Columns
- object m_objRangeColumns = m_objRangeArray.GetType().InvokeMember("Columns", BindingFlags.GetProperty, null, m_objRangeArray, null);
- if (m_objRangeColumns == null)
- {
- Console.WriteLine("出错啦: m_objRangeColumns == null,请检查range的设置。");
- }
- //********************
- try
- {
- m_objRangeColumns.GetType().InvokeMember(_strColumnsPropertyName, BindingFlags.InvokeMethod, null, m_objRangeColumns, _Parameters_Set);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeColumns);
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 列最适应宽度
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <returns></returns>
- public void SetRangeArray_RangeProperty_Columns_AutoFit(string _BeginPoint, string _EndPoint)
- {
- if (m_objSheet == null) { return; }
- this.SetRangeArray_RangeProperty_Columns("AutoFit", null, _BeginPoint, _EndPoint);
- }
- /// <summary>
- /// 设置Rows的属性:行最适应高度
- /// </summary>
- /// <param name="_strColumnsPropertyName">Rows的属性名字</param>
- /// <param name="_Parameters_Set">Rows的属性设置值</param>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <returns></returns>
- internal bool SetRangeArray_RangeProperty_Rows(string _strColumnsPropertyName, object[] _Parameters_Set, string _BeginPoint, string _EndPoint)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- //********************
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- if (m_objRangeArray == null)
- {
- Console.WriteLine("出错啦: m_objRangeArray == null,请检查range的设置。");
- }
- //Columns
- object m_objRangeRows = m_objRangeArray.GetType().InvokeMember("Rows", BindingFlags.GetProperty, null, m_objRangeArray, null);
- if (m_objRangeRows == null)
- {
- Console.WriteLine("出错啦: m_objRangeColumns == null,请检查range的设置。");
- }
- //********************
- try
- {
- m_objRangeRows.GetType().InvokeMember(_strColumnsPropertyName, BindingFlags.InvokeMethod, null, m_objRangeRows, _Parameters_Set);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeRows);
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 行最适应高度
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <returns></returns>
- public void SetRangeArray_RangeProperty_Rows_AutoFit(string _BeginPoint, string _EndPoint)
- {
- if (m_objSheet == null) { return; }
- this.SetRangeArray_RangeProperty_Rows("AutoFit", null, _BeginPoint, _EndPoint);
- }
- /// <summary>
- /// 内部调用: 设置RangeArray属性
- /// </summary>
- /// <param name="_strRangePropertyName">设置RangeArray属性的名字</param>
- /// <param name="_Parameters_Set">设置RangeArray属性的参数值</param>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <returns></returns>
- internal bool SetRangeArray_Property(string _strRangePropertyName, object[] _Parameters_Set, string _BeginPoint, string _EndPoint)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- //********************
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArrayProperty = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- if (m_objRangeArrayProperty == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- //********************
- try
- {
- m_objRangeArrayProperty.GetType().InvokeMember(_strRangePropertyName, BindingFlags.SetProperty, null, m_objRangeArrayProperty, _Parameters_Set);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayProperty);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayProperty);
- GC.GetTotalMemory(true);
- MessageBox.Show("错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 设置水平居中的参数 :2=靠左; 3=居中; 4=靠右
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_nHorizontalAlignment">水平居中的参数 :2=靠左; 3=居中; 4=靠右</param>
- public void SetRangeArray_RangeProperty_HorizontalAlignment(string _BeginPoint, string _EndPoint, int _nHorizontalAlignment)
- {
- if (m_objSheet == null) { return; }
- //水平参数:2=靠左; 3=居中; 4=靠右
- object[] Parameters_Set = new Object[1] { _nHorizontalAlignment }; //HorizontalAlignment
- this.SetRangeArray_Property("HorizontalAlignment", Parameters_Set, _BeginPoint, _EndPoint);
- }
- /// <summary>
- /// 设置垂直居中的参数 :1=靠上 ;2=居中; 3=靠下;
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_nVerticalAlignment">垂直居中的参数 :1=靠上 ;2=居中; 3=靠下</param>
- public void SetRangeArray_RangeProperty_VerticalAlignment(string _BeginPoint, string _EndPoint, int _nVerticalAlignment)
- {
- if (m_objSheet == null) { return; }
- //垂直参数:1=靠上 ;2=居中; 3=靠下;
- object[] Parameters_Set = new Object[1] { _nVerticalAlignment }; //HorizontalAlignment
- this.SetRangeArray_Property("HorizontalAlignment", Parameters_Set, _BeginPoint, _EndPoint);
- }
- /// <summary>
- /// 设置自动换行,或禁止
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_bWrap">自动换行=true ,禁止 =false </param>
- public void SetRangeArray_RangeProperty_WrapText(string _BeginPoint, string _EndPoint, bool _bWrap)
- {
- if (m_objSheet == null) { return; }
- object[] Parameters_Set = new Object[1] { _bWrap }; //
- this.SetRangeArray_Property("WrapText", Parameters_Set, _BeginPoint, _EndPoint);
- }
- /// <summary>
- /// 设置边框的线形
- /// type:1=左边界;2=右边界;3=上边界;4=下边界;5=左上倾斜;6=右上倾斜(以上为对单元格的操作)
- /// type:7=左边界;8=上边界;9=下边界;10=右边界;11=内部垂直边界;12=内部水平边界(以上为对区域的操作)
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_nBordersType">//type:1=左边界;2=右边界;3=上边界;4=下边界;5=左上倾斜;6=右上倾斜(以上为对单元格的操作) 7=左边界;8=上边界;9=下边界;10=右边界;11=内部垂直边界;12=内部水平边界(以上为对区域的操作)</param>
- /// <param name="_nlinestyleValue">__nlinestyleValue:0 =无 1=细实(7=细实)、2=细虚、4=点虚、9=双细实线 </param>
- /// <returns></returns>
- public bool SetRangeArray_Borders_linestyle(string _BeginPoint, string _EndPoint, int _nBordersType, int _nlinestyleValue)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- //_nBordersType: 1=左边界;2=右边界;3=上边界;4=下边界;5=左上倾斜;6=右上倾斜(以上为对单元格的操作)
- // 7=左边界;8=上边界;9=下边界;10=右边界;11=内部垂直边界;12=内部水平边界(以上为对区域的操作)
- //_nlinestyleValue:0 =无 1=细实(7=细实)、2=细虚、4=点虚、9=双细实线
- //public enum XlLineStyle
- //{
- // xlLineStyleNone = -4142,
- // xlDouble = -4119,
- // xlDot = -4118,
- // xlDash = -4115,
- // xlContinuous = 1,
- // xlDashDot = 4,
- // xlDashDotDot = 5,
- // xlSlantDashDot = 13,
- //}
- //********************
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- if (m_objRangeArray == null)
- {
- Console.WriteLine("出错啦: m_objRangeArray == null,请检查range的设置。");
- }
- object[] Parameters_BordersType = new Object[1] { _nBordersType };
- object m_objRangeArrayBorders = m_objRangeArray.GetType().InvokeMember("Borders", BindingFlags.GetProperty, null, m_objRangeArray, Parameters_BordersType);
- if (m_objRangeArrayBorders == null)
- {
- Console.WriteLine("出错啦: m_objRangeArrayProperty == null,请检查range的设置。");
- }
- //********************
- try
- {
- object[] Parameters_BordersValue = new Object[1] { _nlinestyleValue };
- m_objRangeArrayBorders.GetType().InvokeMember("linestyle", BindingFlags.SetProperty, null, m_objRangeArrayBorders, Parameters_BordersValue);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayBorders); //一定要注释,否则出错
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayBorders); //一定要注释,否则出错
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- MessageBox.Show("错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 设置区域内单元格四周边的边框的边界线
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_nlinestyleValue">linestyleValue:0 =无 1=细实(7=细实)、2=细虚、4=点虚、9=双细实线</param>
- public void SetCell_Borders_All_linestyle(string _BeginPoint, string _EndPoint, int _nlinestyleValue)
- {
- if (m_objSheet == null) { return; }
- this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 1, _nlinestyleValue); //左边界
- this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 2, _nlinestyleValue); //右边界
- this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 3, _nlinestyleValue); //上边界
- this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 4, _nlinestyleValue); //下边界
- this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 7, _nlinestyleValue); //左边界
- this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 8, _nlinestyleValue); //右边界
- this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 9, _nlinestyleValue); //上边界
- this.SetRangeArray_Borders_linestyle(_BeginPoint, _EndPoint, 10, _nlinestyleValue); //下边界
- }
- /// <summary>
- /// 设置边框的边界线的厚度
- /// type:1=左边界;2=右边界;3=上边界;4=下边界;5=左上倾斜;6=右上倾斜(以上为对单元格的操作)
- /// type:7=左边界;8=上边界;9=下边界;10=右边界;11=内部垂直边界;12=内部水平边界(以上为对区域的操作)
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_nBordersType">type:1=左边界;2=右边界;3=上边界;4=下边界;5=左上倾斜;6=右上倾斜(以上为对单元格的操作) 7=左边界;8=上边界;9=下边界;10=右边界;11=内部垂直边界;12=内部水平边界(以上为对区域的操作)</param>
- /// <param name="_nBordersValue">val:0无边界线;然后1、2、3、4依次边界线加粗</param>
- /// <returns></returns>
- public bool SetRangeArray_Borders_Weight(string _BeginPoint, string _EndPoint, int _nBordersType, int _nBordersValue)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- //_nBordersType: 1=左边界;2=右边界;3=上边界;4=下边界;5=左上倾斜;6=右上倾斜(以上为对单元格的操作)
- // 7=左边界;8=上边界;9=下边界;10=右边界;11=内部垂直边界;12=内部水平边界(以上为对区域的操作)
- //_nBordersValue:0无边界线;然后1、2、3、4依次边界线加粗
- //public enum XlBorderWeight
- //{
- // xlMedium = -4138,
- // xlHairline = 1,
- // xlThin = 2,
- // xlThick = 4,
- //}
- //********************
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- if (m_objRangeArray == null)
- {
- Console.WriteLine("出错啦: m_objRangeArray == null,请检查range的设置。");
- }
- object[] Parameters_BordersType = new Object[1] { _nBordersType };
- object m_objRangeArrayBorders = m_objRangeArray.GetType().InvokeMember("Borders", BindingFlags.GetProperty, null, m_objRangeArray, Parameters_BordersType);
- if (m_objRangeArrayBorders == null)
- {
- Console.WriteLine("出错啦: m_objRangeArrayBorders == null,请检查range的设置。");
- }
- //********************
- try
- {
- object[] Parameters_BordersValue = new Object[1] { _nBordersValue };
- m_objRangeArrayBorders.GetType().InvokeMember("Weight", BindingFlags.SetProperty, null, m_objRangeArrayBorders, Parameters_BordersValue);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayBorders); //一定要注释,否则出错
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayBorders); //一定要注释,否则出错
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- MessageBox.Show("错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 设置区域内单元格四周边的边框的边界线的厚度
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_nBordersValue">val:0无边界线;然后1、2、3、4依次边界线加粗 </param>
- public void SetCell_Borders_All_Weight(string _BeginPoint, string _EndPoint, int _nBordersValue)
- {
- if (m_objSheet == null) { return; }
- this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 1, _nBordersValue); //左边界
- this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 2, _nBordersValue); //右边界
- this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 3, _nBordersValue); //上边界
- this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 4, _nBordersValue); //下边界
- this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 7, _nBordersValue); //左边界
- this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 8, _nBordersValue); //右边界
- this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 9, _nBordersValue); //上边界
- this.SetRangeArray_Borders_Weight(_BeginPoint, _EndPoint, 10, _nBordersValue); //下边界
- }
- /// <summary>
- /// 内部调用,设置字体的属性
- /// </summary>
- /// <param name="_strFontPropertyName">字体属性的名字</param>
- /// <param name="_Parameters_Set">字体属性的值</param>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <returns></returns>
- internal bool SetRangeArray_Font(string _strFontPropertyName, object[] _Parameters_Set, string _BeginPoint, string _EndPoint)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- //********************
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- object m_objRangeArrayFont = m_objRangeArray.GetType().InvokeMember("Font", BindingFlags.GetProperty, null, m_objRangeArray, null);
- if (m_objRangeArray == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- //********************
- try
- {
- m_objRangeArrayFont.GetType().InvokeMember(_strFontPropertyName, BindingFlags.SetProperty, null, m_objRangeArrayFont, _Parameters_Set);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayFont); //一定要注释,否则出错
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayFont); //一定要注释,否则出错
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- MessageBox.Show("错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 设置前景色
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_nColor">1 =黑色 2 =白色 3 =红色 4 =绿 5 =蓝色 6 =黄色 7=紫红色</param>
- /// <returns></returns>
- public void SetRangeArray_FontProperty_ColorIndex(string _BeginPoint, string _EndPoint, int _nColor)
- {
- //1 =黑色 2 =白色 3 =红色 4 =绿 5 =蓝色 6 =黄色 7=紫红色
- object[] Parameters_Set = new Object[1] { _nColor };
- this.SetRangeArray_Font("ColorIndex", Parameters_Set, _BeginPoint, _EndPoint);
- }
- /// <summary>
- /// 设置字号大小
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_nSize">字号,如12;14;18;32;48</param>
- public void SetRangeArray_FontProperty_Size(string _BeginPoint, string _EndPoint, int _nSize)
- {
- object[] Parameters_Set = new Object[1] { _nSize };
- this.SetRangeArray_Font("Size", Parameters_Set, _BeginPoint, _EndPoint);
- }
- /// <summary>
- /// 设置字体
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_strName">字体的名字,如 "宋体"</param>
- public void SetRangeArray_FontProperty_Name(string _BeginPoint, string _EndPoint, string _strName)
- {
- object[] Parameters_Set = new Object[1] { _strName };
- this.SetRangeArray_Font("Name", Parameters_Set, _BeginPoint, _EndPoint);
- }
- /// <summary>
- /// 设置是否黑体
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_bBold">是否黑体 true = 黑体</param>
- public void SetRangeArray_FontProperty_Bold(string _BeginPoint, string _EndPoint, bool _bBold)
- {
- object[] Parameters_Set = new Object[1] { _bBold };
- this.SetRangeArray_Font("Bold", Parameters_Set, _BeginPoint, _EndPoint);
- }
- /// <summary>
- /// 设置是否下划线
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_bUnderline">是否下划线 true = 加下划线</param>
- public void SetRangeArray_FontProperty_Underline(string _BeginPoint, string _EndPoint, bool _bUnderline)
- {
- object[] Parameters_Set = new Object[1] { _bUnderline };
- this.SetRangeArray_Font("Underline", Parameters_Set, _BeginPoint, _EndPoint);
- }
- /// <summary>
- /// 设置是否斜体
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_bItalic">是否斜体 true = 斜体</param>
- public void SetRangeArray_FontProperty_Italic(string _BeginPoint, string _EndPoint, bool _bItalic)
- {
- object[] Parameters_Set = new Object[1] { _bItalic };
- this.SetRangeArray_Font("Italic", Parameters_Set, _BeginPoint, _EndPoint);
- }
- /// <summary>
- /// 设置属性举例,设置成为 斜体 下划线 黑体 隶书 字号 =18 前景色 =红色 背景色= 黄色
- /// </summary>
- public void SetRangeArray_FontProperty_EG() //
- {
- this.SetRangeArray_FontProperty_Bold("A1", "E8", true);
- this.SetRangeArray_FontProperty_ColorIndex("A1", "E8", 3); //前景色 =红色
- this.SetRangeArray_FontProperty_Italic("A1", "E8", true);
- this.SetRangeArray_FontProperty_Name("A1", "E8", "隶书");
- this.SetRangeArray_FontProperty_Size("A1", "E8", 72);
- this.SetRangeArray_FontProperty_Underline("A1", "E8", true);
- this.SetRangeArray_Property_BackGroundColor("A1", "E8", 7);
- }
- /// <summary>
- /// 设置背景色
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_nColor">1 =黑色 2 =白色 3 =红色 4 =绿 5 =蓝色 6 =黄色 7=紫红色</param>
- /// <returns></returns>
- public bool SetRangeArray_Property_BackGroundColor(string _BeginPoint, string _EndPoint, int _nColor) //
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- //********************
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- object m_objRangeArrayFont = m_objRangeArray.GetType().InvokeMember("Interior", BindingFlags.GetProperty, null, m_objRangeArray, null);
- if (m_objRangeArray == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- //********************
- try
- {
- //*****************************
- //objRange1.Interior.ColorIndex = "5"; //背景色:5=蓝色
- //***************************************************
- object[] Parameters_Set = new Object[1] { _nColor };
- m_objApp.GetType().InvokeMember("ColorIndex", BindingFlags.SetProperty, null, m_objRangeArrayFont, Parameters_Set);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayFont); //一定要注释,否则出错
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArrayFont); //一定要注释,否则出错
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- MessageBox.Show("错误!错误原因:" + ex.Message);
- return false;
- }
- }
- /// <summary>
- /// 得到有效行个数
- /// </summary>
- /// <returns></returns>
- public int GetRange_UsedRangeRowsCount()
- {
- if (m_objApp == null) { return 0; }
- if (m_objSheet == null) { return 0; }
- this.SetApp_Exit_EditMode();
- try
- {
- object m_objUsedRange = m_objSheet.GetType().InvokeMember("UsedRange", BindingFlags.GetProperty, null, m_objSheet, null);
- if (m_objUsedRange == null)
- {
- Console.WriteLine("出错啦: UsedRange == null。");
- }
- object m_objUsedRangeRows = m_objUsedRange.GetType().InvokeMember("Rows", BindingFlags.GetProperty, null, m_objUsedRange, null);
- int UsedRangeRowsCount = (int)m_objUsedRangeRows.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, m_objUsedRangeRows, null);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objUsedRangeRows); //一定要注释,否则出错
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objUsedRange);
- GC.GetTotalMemory(true);
- return UsedRangeRowsCount;
- }
- catch (Exception ex)
- {
- GC.GetTotalMemory(true);
- MessageBox.Show("读取GetRange_UsedRangeRowsCount错误!错误原因:" + ex.Message);
- return 0;
- }
- }
- /// <summary>
- /// 得到有效列的个数
- /// </summary>
- /// <returns></returns>
- public int GetRange_UsedRangeColumnsCount()
- {
- if (m_objApp == null) { return 0; }
- if (m_objSheet == null) { return 0; }
- this.SetApp_Exit_EditMode();
- try
- {
- object m_objUsedRange = m_objSheet.GetType().InvokeMember("UsedRange", BindingFlags.GetProperty, null, m_objSheet, null);
- if (m_objUsedRange == null)
- {
- Console.WriteLine("出错啦: UsedRange == null。");
- }
- object m_objUsedRangeColumns = m_objUsedRange.GetType().InvokeMember("Columns", BindingFlags.GetProperty, null, m_objUsedRange, null);
- int UsedRangeColumnsCount = (int)m_objUsedRangeColumns.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, m_objUsedRangeColumns, null);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objUsedRangeColumns); //一定要注释,否则出错
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objUsedRange);
- GC.GetTotalMemory(true);
- return UsedRangeColumnsCount;
- }
- catch (Exception ex)
- {
- MessageBox.Show("读取GetRange_UsedRangeColumnsCount错误!错误原因:" + ex.Message);
- return 0;
- }
- }
- /// <summary>
- /// 得到已经使用的区域
- /// </summary>
- /// <returns></returns>
- public string GetRange_UsedRange()
- {
- //System.Collections.ArrayList alUsedRange = new System.Collections.ArrayList();
- string strUsedRange;
- try
- {
- int nUsedRangeColumnsCount = this.GetRange_UsedRangeColumnsCount();
- int nUsedRangeRowsCount = this.GetRange_UsedRangeRowsCount();
- strUsedRange = SuperTools.UC_EmbedExcelIntoWinFormNoDLL.Tool_NtoL(nUsedRangeColumnsCount) + nUsedRangeRowsCount.ToString();
- return strUsedRange;
- }
- catch (Exception ex)
- {
- MessageBox.Show("读取GetRange_UsedRange错误!错误原因:" + ex.Message);
- return null;
- }
- }
- /// <summary>
- /// 设置整个使用区域,全部自动最适应列框
- /// </summary>
- /// <returns></returns>
- public void SetRange_UsedRange_AutoFit()
- {
- string ss = this.GetRange_UsedRange();
- this.SetRangeArray_RangeProperty_Columns_AutoFit("A1", ss);
- this.SetRangeArray_RangeProperty_Rows_AutoFit("A1", ss);
- }
- /// <summary>
- /// 设置单元格的格式 ,如:"#,##0.00_" = 数字格式
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <param name="_strFormatStyle"></param>
- /// <returns></returns>
- public bool SetRangeArray_FormatStyle(string _BeginPoint, string _EndPoint, string _strFormatStyle)
- {
- if (m_objApp == null) { return false; }
- if (m_objSheet == null) { return false; }
- this.SetApp_Exit_EditMode();
- try
- {
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "C1", "C5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- if (m_objRangeArray == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- //得到写入值
- Object[] ParametersArray_WriteValue = new Object[1];
- ParametersArray_WriteValue[0] = _strFormatStyle; //赋值
- //******************
- m_objRangeArray.GetType().InvokeMember("NumberFormat", BindingFlags.SetProperty, null, m_objRangeArray, ParametersArray_WriteValue);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("设置数字格式错误!错误原因:" + ex.Message);
- return false;
- }
- //G/通用格式
- //"#,##0.00_ "
- }
- /// <summary>
- /// 获取单元格的格式
- /// </summary>
- /// <param name="_BeginPoint">起始位置 如"A1"</param>
- /// <param name="_EndPoint">终止位置 如"B5"</param>
- /// <returns></returns>
- public string GetRangeArray_FormatStyle(string _BeginPoint, string _EndPoint)
- {
- if (m_objApp == null) { return String.Empty; }
- if (m_objSheet == null) { return String.Empty; }
- this.SetApp_Exit_EditMode();
- try
- {
- //得到range数组
- //object[] Parameters_rangeArray = new object[] { "C1", "C5" };
- object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
- object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
- if (m_objRangeArray == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- //NumberFormatLocal //NumberFormat
- string strColumn_NumberFormatLocal = (string)m_objRangeArray.GetType().InvokeMember("NumberFormat", BindingFlags.GetProperty, null, m_objRangeArray, null);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
- GC.GetTotalMemory(true);
- return strColumn_NumberFormatLocal; //
- }
- catch (Exception ex)
- {
- MessageBox.Show("获取单元格的格式GetRangeArray_FormatStyle错误!错误原因:" + ex.Message);
- return null;
- }
- //G/通用格式
- //"#,##0.00_ "
- }
- #region 学习用
- /*
- //根据DataTable的字段的数据类型来设置excel列的数据格式
- DataTable table = new DataTable();
- int i = 0;
- foreach (DataColumn column in table.Columns)
- {
- i++;
- // Insert fieldname
- object range = m_objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, m_objSheet, new object[2] { 1, i });
- if (range == null)
- {
- Console.WriteLine("出错啦: range == null,请检查range的设置。");
- }
- range.GetType().InvokeMember("Value", BindingFlags.SetProperty | BindingFlags.OptionalParamBinding, null, range, new object[1] { column.ColumnName });
- object[] format = null;
- if (column.DataType.Equals(typeof(double)))
- {
- string s = "0" +
- System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
- for (int digits = 0; digits < System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalDigits; digits++)
- {
- s += "0";
- }
- format = new object[] { s.ToString() };
- }
- else if (column.DataType.Equals(typeof(int)))
- {
- format = new object[] { "0" };
- }
- else if (column.DataType.Equals(typeof(Int16)))
- {
- format = new object[] { "0" };
- }
- else if (column.DataType.Equals(typeof(DateTime)))
- {
- format = new object[] { "TT.MM.JJJJ HH:mm:ss" };
- }
- else if (column.DataType.Equals(typeof(string)))
- {
- format = new object[] { "" };
- }
- //Excel.Range oRange = (Excel.Range)ws.Columns[SpaltenNummer, Type.Missing];
- range = m_objSheet.GetType().InvokeMember("Columns", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, m_objSheet, new object[2] { i, Type.Missing });
- //range = sheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, sheet, new object[2] { 2, i });
- //range.GetType().InvokeMember("EntireColumn", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, range, new object[0]).GetType().InvokeMember("NumberFormat", BindingFlags.SetProperty | BindingFlags.OptionalParamBinding, null, range, format);
- range.GetType().InvokeMember("NumberFormat", BindingFlags.SetProperty | BindingFlags.OptionalParamBinding, null, range, format);
- }
- */
- #endregion
- #region 字母转换为数字 数字转换为字母
- ///<summary>
- /// 字母转换为数字,Excel列头,如A-1;AA-27
- /// </summary>
- /// <param name="strLetter">字母</param>
- /// <returns>字母对应的数字</returns>
- public static int Tool_LtoN(string strLetter)
- {
- int intRtn = 0;
- string strLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- if (strLetter.Length == 2)
- intRtn += (strLetters.IndexOf(strLetter.Substring(0, 1)) + 1) * 26;
- intRtn += strLetters.IndexOf(strLetter.Substring(strLetter.Length - 1, 1)) + 1;
- return intRtn;
- }
- /// <summary>
- /// 数字转换为字母,Excel列头,如1-A;27-AA
- /// </summary>
- /// <param name="intNumber">数字</param>
- /// <returns>数字对应的字母</returns>
- public static string Tool_NtoL(int intNumber)
- {
- if (intNumber > 702)
- return String.Empty;
- if (intNumber == 702)
- return "ZZ";
- string strRtn = String.Empty;
- string strLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- if (intNumber == 26)
- {
- strRtn = "Z";
- }
- else
- {
- if (intNumber > 26)
- strRtn = strLetters.Substring(intNumber / 26 - 1, 1);
- strRtn += strLetters.Substring((intNumber % 26) - 1, 1);
- }
- return strRtn;
- }
- #endregion 辅助函数
- #region 从excel文件得到GetDataTable
- /// <summary>
- /// 读取excel打开的文件,如xls、xml、csv等文件的内容,写入到DataTable中
- /// </summary>
- /// <returns></returns>
- public DataTable Tools_GetDataTableFromExcelSheet()
- {
- object[] m_Parameters;
- System.Data.DataTable _Table = new System.Data.DataTable();
- #region 读取第一行内容作为写入字段名
- //********************************************************************************
- System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
- int ColumnNumber = 1;
- while (true) //读取第一行内容作为写入字段名
- {
- m_Parameters = new object[2] { 1, ColumnNumber }; ; //第一行是字段名
- object m_objCells = m_objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, m_objSheet, m_Parameters);
- object m_objCellsValue = m_objCells.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, m_objCells, new object[0]);
- if (m_objCellsValue == null) //有空则退出,不再继续管后面的列
- {
- break;
- }
- else
- {
- ColumnNumber++;
- string strTemp = m_objCellsValue.ToString();
- ParaColumns.Add(strTemp + "|String"); //System.String
- }
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objCells);
- GC.GetTotalMemory(true);
- }
- SuperTools.DataTableTools.Add_Columns(ref _Table, ParaColumns); //增加列
- //********************************************************************************
- #endregion
- #region 读取excel的数据项
- //********************************************************************************
- int RowNumber = 1; //增加行
- while (true) //读取除第一行以外的内容
- {
- object[] ColumnValue = new object[_Table.Columns.Count]; //定义该行的各列
- for (int j = 0; j < _Table.Columns.Count; j++)
- {
- m_Parameters = new object[2] { RowNumber + 1, j + 1 }; //第i行,第j列
- object m_objCells = m_objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, m_objSheet, m_Parameters);
- object m_objCellsValue = m_objCells.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, m_objCells, new object[0]); //读值
- //m_objCells.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, m_objCells, Parameters); //写值
- //if (m_objCellsValue == null || m_objCellsValue.ToString().Trim() == String.Empty)
- if (m_objCellsValue != null)
- {
- ColumnValue[j] = m_objCellsValue.ToString();
- }
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objCells);
- GC.GetTotalMemory(true);
- }
- if (ColumnValue[0] == null) //第1列的该行为,空,则不再增加新行
- {
- break;
- }
- else
- {
- _Table.Rows.Add(ColumnValue); //增加该行
- RowNumber++; //下一行
- }
- }
- //********************************************************************************
- #endregion
- return _Table;
- }
- #endregion
- #endregion
- #region 保存、退出
- /// <summary>
- /// excel保存的文件格式
- /// </summary>
- public enum XlFileFormat
- {
- #region 枚举excel文件的格式
- /// <summary>
- ///
- /// </summary>
- xlCurrentPlatformText = -4158,
- /// <summary>
- ///
- /// </summary>
- xlWorkbookNormal = -4143,
- /// <summary>
- ///
- /// </summary>
- xlSYLK = 2,
- /// <summary>
- ///
- /// </summary>
- xlWKS = 4,
- /// <summary>
- ///
- /// </summary>
- xlWK1 = 5,
- /// <summary>
- ///
- /// </summary>
- xlCSV = 6,
- /// <summary>
- ///
- /// </summary>
- xlDBF2 = 7,
- /// <summary>
- ///
- /// </summary>
- xlDBF3 = 8,
- /// <summary>
- ///
- /// </summary>
- xlDIF = 9,
- /// <summary>
- ///
- /// </summary>
- xlDBF4 = 11,
- /// <summary>
- ///
- /// </summary>
- xlWJ2WD1 = 14,
- /// <summary>
- ///
- /// </summary>
- xlWK3 = 15,
- /// <summary>
- ///
- /// </summary>
- xlExcel2 = 16,
- /// <summary>
- ///
- /// </summary>
- xlTemplate = 17,
- /// <summary>
- ///
- /// </summary>
- xlAddIn = 18,
- /// <summary>
- ///
- /// </summary>
- xlTextMac = 19,
- /// <summary>
- ///
- /// </summary>
- xlTextWindows = 20,
- /// <summary>
- ///
- /// </summary>
- xlTextMSDOS = 21,
- /// <summary>
- ///
- /// </summary>
- xlCSVMac = 22,
- /// <summary>
- ///
- /// </summary>
- xlCSVWindows = 23,
- /// <summary>
- ///
- /// </summary>
- xlCSVMSDOS = 24,
- /// <summary>
- ///
- /// </summary>
- xlIntlMacro = 25,
- /// <summary>
- ///
- /// </summary>
- xlIntlAddIn = 26,
- /// <summary>
- ///
- /// </summary>
- xlExcel2FarEast = 27,
- /// <summary>
- ///
- /// </summary>
- xlWorks2FarEast = 28,
- /// <summary>
- ///
- /// </summary>
- xlExcel3 = 29,
- /// <summary>
- ///
- /// </summary>
- xlWK1FMT = 30,
- /// <summary>
- ///
- /// </summary>
- xlWK1ALL = 31,
- /// <summary>
- ///
- /// </summary>
- xlWK3FM3 = 32,
- /// <summary>
- ///
- /// </summary>
- xlExcel4 = 33,
- /// <summary>
- ///
- /// </summary>
- xlWQ1 = 34,
- /// <summary>
- ///
- /// </summary>
- xlExcel4Workbook = 35,
- /// <summary>
- ///
- /// </summary>
- xlTextPrinter = 36,
- /// <summary>
- ///
- /// </summary>
- xlWK4 = 38,
- /// <summary>
- ///
- /// </summary>
- xlExcel7 = 39,
- /// <summary>
- ///
- /// </summary>
- xlExcel5 = 39,
- /// <summary>
- ///
- /// </summary>
- xlWJ3 = 40,
- /// <summary>
- ///
- /// </summary>
- xlWJ3FJ3 = 41,
- /// <summary>
- ///
- /// </summary>
- xlUnicodeText = 42,
- /// <summary>
- ///
- /// </summary>
- xlExcel9795 = 43,
- /// <summary>
- ///
- /// </summary>
- xlHtml = 44,
- /// <summary>
- ///
- /// </summary>
- xlWebArchive = 45,
- /// <summary>
- ///
- /// </summary>
- xlXMLSpreadsheet = 46,
- #endregion
- }
- /// <summary>
- /// 文件保存
- /// </summary>
- /// <returns></returns>
- public bool AppExcel_Save()
- {
- if (m_objApp == null) { return false; }
- if (m_objBook == null) { return false; }
- SetApp_Exit_EditMode(); //退出编辑模式
- try
- {
- //m_objApp.GetType().InvokeMember("Save", BindingFlags.InvokeMethod, null, m_objApp, null); //ok
- m_objBook.GetType().InvokeMember("Save", BindingFlags.InvokeMethod, null, m_objBook, null); //ok
- //m_objSheet.GetType().InvokeMember("Save", BindingFlags.InvokeMethod, null, m_objSheet, null);//不能通过,必须SaveAs
- return true;
- }
- catch (Exception ex)
- {
- string strErr = "Excel.Application保存时出错!出错原因:" + ex.Message;
- System.Windows.Forms.MessageBox.Show(strErr);
- return true;
- }
- }
- /// <summary>
- /// Excel保存
- /// </summary>
- /// <param name="m_strFileName">m_strFileName可以选择= null 或者 = "" </param>
- public bool AppExcel_SaveAs(string m_strFileName)
- {
- if (m_objApp == null) { return false; }
- if (m_objBook == null) { return false; }
- SetApp_Exit_EditMode(); //退出编辑模式
- try
- {
- //不提示保存
- try
- {
- object[] m_Parameters_DisplayAlerts = new Object[1] { false };
- m_objApp.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, m_objApp, m_Parameters_DisplayAlerts);
- }
- catch { }
- if (m_strFileName == null || m_strFileName == "")
- {
- //不改名保存
- m_objBook.GetType().InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, m_objBook, null);
- }
- else
- {
- //另存为
- #region 另存为参数
- object o_Filename = m_strFileName; // "123";
- object o_FileFormat = System.Reflection.Missing.Value; // 缺省值
- //object o_FileFormat = 1; //正常的excel的工作簿(bin文件)
- //object o_FileFormat = XlFileFormat.xlXMLSpreadsheet ;
- object o_Password = System.Reflection.Missing.Value;
- object o_WriteResPassword = System.Reflection.Missing.Value;
- object o_ReadOnlyRecommended = System.Reflection.Missing.Value;
- object o_CreateBackup = System.Reflection.Missing.Value;
- object o_Excel_XlSaveAsAccessMode_AccessMode = System.Reflection.Missing.Value;
- object o_ConflictResolution = System.Reflection.Missing.Value;
- object o_AddToMru = System.Reflection.Missing.Value;
- object o_TextCodepage = System.Reflection.Missing.Value;
- object o_TextVisualLayout = System.Reflection.Missing.Value;
- object o_Local = System.Reflection.Missing.Value;
- if (m_strFileName.Length > 4 && m_strFileName.Substring(m_strFileName.Length - 4, 4).ToLower() == ".xls")
- {
- o_FileFormat = 1; //正常的excel的工作簿(bin文件) ok
- o_FileFormat = XlFileFormat.xlWorkbookNormal;
- }
- if (m_strFileName.Length > 4 && m_strFileName.Substring(m_strFileName.Length - 4, 4).ToLower() == ".csv")
- {
- o_FileFormat = XlFileFormat.xlCSV;
- }
- if (m_strFileName.Length > 4 && m_strFileName.Substring(m_strFileName.Length - 4, 4).ToLower() == ".xml")
- {
- o_FileFormat = XlFileFormat.xlXMLSpreadsheet;
- }
- object[] m_Parameters_objBookSaveAs = new Object[12];
- m_Parameters_objBookSaveAs[0] = o_Filename;
- m_Parameters_objBookSaveAs[1] = o_FileFormat;
- m_Parameters_objBookSaveAs[2] = o_Password;
- m_Parameters_objBookSaveAs[3] = o_WriteResPassword;
- m_Parameters_objBookSaveAs[4] = o_ReadOnlyRecommended;
- m_Parameters_objBookSaveAs[5] = o_CreateBackup;
- m_Parameters_objBookSaveAs[6] = o_Excel_XlSaveAsAccessMode_AccessMode;
- m_Parameters_objBookSaveAs[7] = o_ConflictResolution;
- m_Parameters_objBookSaveAs[8] = o_AddToMru;
- m_Parameters_objBookSaveAs[9] = o_TextCodepage;
- m_Parameters_objBookSaveAs[10] = o_TextVisualLayout;
- m_Parameters_objBookSaveAs[11] = o_Local;
- #endregion
- m_objBook.GetType().InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, m_objBook, m_Parameters_objBookSaveAs);
- }
- return true;
- ////退出
- //m_objApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, m_objApp, null);
- }
- catch (Exception ex)
- {
- string strErr = "Excel.Application保存时出错!出错原因:" + ex.Message;
- System.Windows.Forms.MessageBox.Show(strErr);
- return true;
- }
- }
- /// <summary>
- /// Excel退出
- /// </summary>
- /// <returns></returns>
- public void AppExcel_Exit() //退出时报错
- {
- //if (m_objApp == null) { return false; }
- //if (m_objBook == null) { return false; }
- #region 退出 注销
- try
- {
- //不提示保存
- object[] m_Parameters_DisplayAlerts = new Object[1] { false };
- m_objApp.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, m_objApp, m_Parameters_DisplayAlerts);
- }
- catch { };
- //********************************************************************************
- try
- {
- #region 关闭参数
- object o_save_changes = false;
- object o_Filename = System.Reflection.Missing.Value;
- object o_route_workbook = System.Reflection.Missing.Value;
- #endregion
- object[] m_Parameters_objBookClose = new Object[3];
- m_Parameters_objBookClose[0] = o_save_changes;
- m_Parameters_objBookClose[1] = o_Filename;
- m_Parameters_objBookClose[2] = o_route_workbook;
- //退出Book
- m_objBook.GetType().InvokeMember("Close", BindingFlags.InvokeMethod, null, m_objBook, m_Parameters_objBookClose);
- //m_objBook.GetType().InvokeMember("Close", BindingFlags.InvokeMethod, null, m_objBook, null); //ok
- //退出Books
- m_objBooks.GetType().InvokeMember("Close", BindingFlags.InvokeMethod, null, m_objBooks, null);
- m_objApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, m_objApp, null);
- //return true;
- }
- catch (Exception ex)
- {
- string strErr = "Excel.Application退出时出错!出错原因:" + ex.Message;
- //System.Windows.Forms.MessageBox.Show(strErr);
- //return false;
- }
- finally
- {
- //System.Runtime.InteropServices.Marshal.ReleaseComObject(objCells);
- if (m_objSheet != null)
- {
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet);
- GC.GetTotalMemory(true);
- }
- if (m_objSheets != null)
- {
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheets);
- GC.GetTotalMemory(true);
- }
- if (m_objBook != null)
- {
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBook);
- GC.GetTotalMemory(true);
- }
- if (m_objBooks != null)
- {
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBooks);
- GC.GetTotalMemory(true);
- }
- if (m_objApp != null)
- {
- System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objApp);
- GC.GetTotalMemory(true);
- }
- GC.Collect(); //强制对所有代进行垃圾回收
- }
- #endregion
- //如果再有错误,弹出“Microsoft Office Excel 遇到问题需要关闭。我们对此引起的不便表示抱歉” ,则杀死该进程
- try
- {
- this.Tools_KillExceProcess(this.LateBindingExcelStartTime, this.LateBindingExcelEndTime);
- }
- catch (Exception ex)
- {
- MessageBox.Show("杀死进程错误:" + ex.Message);
- }
- }
- #endregion
- /// <summary>
- /// 杀死Excel.exe的进程
- /// </summary>
- /// <param name="beforeTime">Excel.exe进程的启动时间</param>
- /// <param name="afterTime">Excel.exe进程启动完毕后的时间</param>
- public void Tools_KillExceProcess(DateTime beforeTime, DateTime afterTime)
- {
- System.Diagnostics.Process[] myProcesses;
- DateTime startTime;
- myProcesses = System.Diagnostics.Process.GetProcessesByName("Excel");
- //得不到Excel进程ID,暂时只能判断进程启动时间
- foreach (System.Diagnostics.Process myProcess in myProcesses)
- {
- startTime = myProcess.StartTime;
- if (startTime >= beforeTime && startTime <= afterTime)
- {
- myProcess.Kill();
- }
- }
- }
- #endregion
- #region 窗体嵌入到父窗体,并重画
- /// <summary>
- /// 子窗体嵌入到父窗体
- /// </summary>
- private void EmbedIntoWindows()
- {
- #region 删除式样文件
- //Environment.UserName
- //System.Environment.UserDomainName
- //WindowsIdentity.GetCurrent(false).Name;
- //C:\Documents and Settings\Administrator\Application Data\Microsoft\Excel\Excel11.xlb
- string LoginName = System.Environment.UserName; //计算机名字
- string strExcelStyleFileName = "C:\\Documents and Settings\\" + LoginName + "\\Application Data\\Microsoft\\Excel\\Excel11.xlb";
- if (System.IO.File.Exists(strExcelStyleFileName) == true)
- {
- System.IO.File.Delete(strExcelStyleFileName);
- }
- #endregion
- #region
- if (this.appSubWinHandle == IntPtr.Zero)
- {
- MessageBox.Show("没有指定子窗体的句柄:appSubWinHandle");
- }
- #endregion
- myWin32API.SetParent(this.appSubWinHandle, this.Handle); //子窗体嵌入到父窗体
- //****************************************************************************
- //设置显示式样
- //myWin32API.SetWindowLong(this.appSubWinHandle, myWin32API.GWL_STYLE, new IntPtr(myWin32API.WS_VISIBLE)); //全部显示okokok
- //****************************************************************************
- int nNewStyle = myWin32API.GetWindowLong(this.appSubWinHandle, myWin32API.GWL_STYLE);
- //nNewStyle &= ~myWin32API.WS_SYSMENU; //去掉将window的关闭按钮和最大最小化按钮,但是需要显示title
- //nNewStyle &= ~myWin32API.WS_EX_TOOLWINDOW; //去掉将window的关闭按钮,但是需要显示title和最大最小化按钮
- nNewStyle &= ~myWin32API.WS_DLGFRAME; //去掉Micrisoft标题栏title
- //nNewStyle &= ~myWin32API.WS_BORDER; //
- //**************************************************
- //**************************************************
- /*
- //**************************************************
- int hMenu = myWin32API.GetSystemMenu((Int32)this.appSubWinHandle, false);
- int menuItemCount = myWin32API.GetMenuItemCount(hMenu);
- if (hMenu > 0)
- {
- for (int i = 0; i <= menuItemCount + 1; i++)
- {
- int y = myWin32API.GetMenuItemID(hMenu, i);
- int x = myWin32API.RemoveMenu(hMenu, i, myWin32API.MF_REMOVE);
- }
- }
- myWin32API.DrawMenuBar((Int32)this.appSubWinHandle);
- //**********************************************************************************************************
- IntPtr hSysMenu = myWin32API.GetSystemMenu(this.appSubWinHandle, 0);
- int xxx= myWin32API.DeleteMenu(hSysMenu, 0xF060, myWin32API.MF_BYCOMMAND);
- if (hMenu > 0)
- {
- for (int i = 0; i <= menuItemCount + 1; i++)
- {
- int xx = myWin32API.DeleteMenu(hSysMenu, 0xF060, myWin32API.MF_BYCOMMAND);
- //int x = myWin32API.DeleteMenu((IntPtr)hMenu, i, myWin32API.MF_BYPOSITION | myWin32API.MF_BYCOMMAND);
- }
- }
- myWin32API.DrawMenuBar((Int32)this.appSubWinHandle);
- //**********************************************************************************************************
- try
- {
- //if (hMenu > 0)
- //{
- // int menuItemCount =myWin32API. GetMenuItemCount(hMenu);
- // myWin32API.RemoveMenu(hMenu, menuItemCount - 1, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
- // myWin32API.RemoveMenu(hMenu, menuItemCount - 2, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
- // myWin32API.RemoveMenu(hMenu, menuItemCount - 3, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
- // myWin32API.RemoveMenu(hMenu, menuItemCount - 4, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
- // myWin32API.RemoveMenu(hMenu, menuItemCount - 5, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
- // myWin32API.RemoveMenu(hMenu, menuItemCount - 6, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
- // myWin32API.RemoveMenu(hMenu, menuItemCount - 7, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
- // //myWin32API.RemoveMenu(hMenu, menuItemCount - 8, myWin32API.MF_REMOVE | myWin32API.MF_BYPOSITION);
- // myWin32API.DrawMenuBar((Int32)this.appSubWinHandle);
- //}
- }
- catch (Exception ex)
- {
- System.Windows.Forms.MessageBox.Show("移除系统菜单出错" + ex.Message);
- }
- */
- //**************************************************
- //**************************************************
- //***********************
- myWin32API.SetWindowLong(this.appSubWinHandle, myWin32API.GWL_STYLE, nNewStyle); //设置窗口新式样
- ReDraw();
- ReDraw();
- //***********************
- }
- //重画
- private void ReDraw()
- {
- if (this.appSubWinHandle != IntPtr.Zero)
- {
- //myWin32API.MoveWindow(this.appSubWinHandle, 0, 0, this.Width, this.Height, true);
- //myWin32API.SetWindowPos2(this.appSubWinHandle.ToInt32(), this.Handle.ToInt32(),
- // 0, 0,
- // this.Bounds.Width + 20, this.Bounds.Height + 20,
- // myWin32API.SWP_NOZORDER | myWin32API.SWP_NOMOVE | myWin32API.SWP_DRAWFRAME);
- myWin32API.SetWindowPos(this.appSubWinHandle, this.Handle,
- 0, 0,
- this.Bounds.Width, this.Bounds.Height,
- myWin32API.SWP_NOZORDER | myWin32API.SWP_NOMOVE | myWin32API.SWP_DRAWFRAME);
- myWin32API.MoveWindow(this.appSubWinHandle, 0, 0, this.Width, this.Height, true); // Move the window to overlay it on this window
- }
- if (this.Parent != null)
- {
- this.Parent.Focus();
- }
- }
- #endregion
- }
- #endregion
- #region (静态类) 调用 API函数
- /// <summary>
- /// 调用 API函数
- /// </summary>
- public class myWin32API
- {
- #region 得到当前窗体的句柄
- //GetFocus()得到的肯定是ActiveWindow,但是GetActiveWindow()的窗口不一定是有输入焦点的窗口。
- //GetForegroundWindow()是和窗口在Z-ORDER里的位置有关的。
- //比如说一个ACTIVE WINDOW上面还有一个NOT ACTIVE WINDOW,但这个窗口的属性是TOPMOST。GetForegroundWindow()只能取得上面的这个窗口
- /// <summary>
- /// Win32: GetForegroundWindow()
- /// </summary>
- /// <returns></returns>
- [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
- public static extern IntPtr GetForegroundWindow(); //获得当前活动窗口句柄
- /// <summary>
- /// Win32: GetFocus()
- /// </summary>
- /// <returns></returns>
- [DllImport("user32.dll", CharSet = CharSet.Auto)]
- public static extern IntPtr GetFocus();
- /// <summary>
- ///
- /// </summary>
- /// <param name="hwnd"></param>
- /// <returns></returns>
- [DllImport("user32.dll ")]
- public static extern int SetFocus(IntPtr hwnd);
- /// <summary>
- ///
- /// </summary>
- /// <returns></returns>
- [DllImport("User32.DLL")]
- public static extern IntPtr GetActiveWindow();
- #endregion
- #region 模拟鼠标的移动、点击等动作
- /// <summary>
- /// 该函数可以改变鼠标指针的位置。其中X,Y是相对于屏幕左上角的绝对位置。
- /// </summary>
- /// <param name="X"></param>
- /// <param name="Y"></param>
- /// <returns></returns>
- [DllImport("user32.dll")]
- static extern bool SetCursorPos(int X, int Y);
- /// <summary>
- /// 可以设置鼠标指针绝对的位置,而且可以以相对坐标来设置。另外,该函数还可以模拟鼠标左右键点击、鼠标滚轮操作等。
- /// </summary>
- /// <param name="flags">一个基于uint类型的枚举,鼠标d的动作类型</param>
- /// <param name="dx"></param>
- /// <param name="dy"></param>
- /// <param name="data"></param>
- /// <param name="extraInfo"></param>
- [DllImport("user32.dll")]
- static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);
- [Flags]
- enum MouseEventFlag : uint
- {
- Move = 0x0001,
- LeftDown = 0x0002,
- LeftUp = 0x0004,
- RightDown = 0x0008,
- RightUp = 0x0010,
- MiddleDown = 0x0020,
- MiddleUp = 0x0040,
- XDown = 0x0080,
- XUp = 0x0100,
- Wheel = 0x0800,
- VirtualDesk = 0x4000,
- Absolute = 0x8000
- }
- #endregion
- #region 定义API方法
- /// <summary>
- ///
- /// </summary>
- /// <param name="hWnd"></param>
- /// <param name="nCmdShow"></param>
- /// <returns></returns>
- [DllImport("user32.dll")]
- public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
- /// <summary>
- ///
- /// </summary>
- /// <param name="hWnd"></param>
- /// <returns></returns>
- [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
- public static extern bool SetForegroundWindow(IntPtr hWnd);
- /// <summary>
- ///
- /// </summary>
- /// <param name="hWnd"></param>
- /// <returns></returns>
- [DllImport("user32.dll")]
- public static extern bool IsIconic(IntPtr hWnd);
- /// <summary>
- ///
- /// </summary>
- /// <param name="hWnd"></param>
- /// <returns></returns>
- [DllImport("user32.dll")]
- public static extern bool IsZoomed(IntPtr hWnd);
- #region //********API32函数声明**************
- // **********************************************************************
- //// Win32: SetWindowsHookEx()
- //[DllImport("user32.dll", CharSet = CharSet.Auto,
- // CallingConvention = CallingConvention.StdCall)]
- //private static extern IntPtr SetWindowsHookEx(HookType code,
- // HookProc func,
- // IntPtr hInstance,
- // int threadID);
- /// <summary>
- /// Win32: UnhookWindowsHookEx()
- /// </summary>
- /// <param name="hhook"></param>
- /// <returns></returns>
- [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
- public static extern int UnhookWindowsHookEx(IntPtr hhook);
- /// <summary>
- /// Win32: CallNextHookEx()
- /// </summary>
- /// <param name="hhook"></param>
- /// <param name="nCode"></param>
- /// <param name="wParam"></param>
- /// <param name="lParam"></param>
- /// <returns></returns>
- [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
- public static extern int CallNextHookEx(IntPtr hhook, int nCode, int wParam, IntPtr lParam);
- /// <summary>
- /// Win32: GetModuleHandle()
- /// </summary>
- /// <param name="lpModuleName"></param>
- /// <returns></returns>
- [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
- private static extern IntPtr GetModuleHandle(string lpModuleName);
- /// <summary>
- ///
- /// </summary>
- /// <param name="hWnd"></param>
- /// <param name="ProcessId"></param>
- /// <returns></returns>
- [DllImport("user32.dll")]
- public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId); ////获得活动窗口的线程号
- /// <summary>
- /// Win32: GetWindowThreadProcessId()
- /// </summary>
- /// <param name="hwnd"></param>
- /// <param name="lpdwProcessId"></param>
- /// <returns></returns>
- [DllImport("user32.dll", CharSet = CharSet.Auto)]
- public static extern int GetWindowThreadProcessId(IntPtr hwnd, int lpdwProcessId); ////获得活动窗口的线程号
- /// <summary>
- /// Win32: GetCurrentThreadId
- /// </summary>
- /// <returns></returns>
- [DllImport("kernel32.dll", EntryPoint = "GetCurrentThreadId")]
- public static extern int GetCurrentThreadId();
- /// <summary>
- /// Win32: AttachThreadInput()
- /// </summary>
- /// <param name="idAttach"></param>
- /// <param name="idAttachTo"></param>
- /// <param name="fAttach"></param>
- /// <returns></returns>
- [DllImport("user32.dll", CharSet = CharSet.Auto)]
- private static extern int AttachThreadInput(int idAttach, int idAttachTo, int fAttach);
- /// <summary>
- ///
- /// </summary>
- /// <param name="idAttach"></param>
- /// <param name="idAttachTo"></param>
- /// <param name="fAttach"></param>
- /// <returns></returns>
- [DllImport("user32.dll")]
- public static extern IntPtr AttachThreadInput(IntPtr idAttach, IntPtr idAttachTo, int fAttach);
- /// <summary>
- /// Win32: SendMessage()
- /// </summary>
- /// <param name="hwnd"></param>
- /// <param name="wMsg"></param>
- /// <param name="wParam"></param>
- /// <param name="lParam"></param>
- /// <returns></returns>
- [DllImport("user32.dll", CharSet = CharSet.Auto)]
- private static extern int SendMessage(HandleRef hwnd, int wMsg, int wParam, int lParam);
- /// <summary>
- ///
- /// </summary>
- /// <param name="hwnd"></param>
- /// <param name="wMsg"></param>
- /// <param name="wParam"></param>
- /// <param name="lParam"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
- public static extern int SendMessageString(HandleRef hwnd, int wMsg, int wParam, StringBuilder lParam);
- /// <summary>
- /// Win32: GetWindowText()
- /// </summary>
- /// <param name="hwnd"></param>
- /// <param name="lpString"></param>
- /// <param name="nMaxCount"></param>
- /// <returns></returns>
- [DllImport("user32.dll", CharSet = CharSet.Auto)]
- private static extern int GetWindowText(IntPtr hwnd, StringBuilder lpString, int nMaxCount);
- /// <summary>
- /// Win32: GetClassName()
- /// </summary>
- /// <param name="hwnd"></param>
- /// <param name="lpClassName"></param>
- /// <param name="nMaxCount"></param>
- /// <returns></returns>
- [DllImport("user32.dll", CharSet = CharSet.Auto)]
- private static extern int GetClassName(IntPtr hwnd, StringBuilder lpClassName, int nMaxCount);
- #endregion
- #region DDE学习用
- //*************************
- /// <summary>
- ///
- /// </summary>
- /// <param name="hwnd"></param>
- /// <param name="nIDEvent"></param>
- /// <param name="uElapse"></param>
- /// <param name="lpTimerFunc"></param>
- /// <returns></returns>
- [DllImport("user32.dll", SetLastError = true)]
- public static extern long SetTimer(IntPtr hwnd, long nIDEvent, long uElapse, long lpTimerFunc);
- /// <summary>
- ///
- /// </summary>
- /// <param name="hwnd"></param>
- /// <param name="nIDEvent"></param>
- /// <returns></returns>
- [DllImport("user32.dll", SetLastError = true)]
- public static extern long KillTimer(IntPtr hwnd, long nIDEvent);
- //************************
- /// <summary>
- ///
- /// </summary>
- /// <param name="idInst"></param>
- /// <param name="hszService"></param>
- /// <param name="hszTopic"></param>
- /// <param name="pCC"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "DdeConnect", CharSet = CharSet.Ansi)]
- public static extern IntPtr DdeConnect(uint idInst, IntPtr hszService, IntPtr hszTopic, IntPtr pCC);
- /// <summary>
- ///
- /// </summary>
- /// <param name="idInst"></param>
- /// <param name="pSrc"></param>
- /// <param name="cb"></param>
- /// <param name="cbOff"></param>
- /// <param name="hszItem"></param>
- /// <param name="wFmt"></param>
- /// <param name="afCmd"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "DdeCreateDataHandle", CharSet = CharSet.Ansi)]
- public static extern IntPtr DdeCreateDataHandle(
- uint idInst, byte[] pSrc, uint cb, uint cbOff, IntPtr hszItem, uint wFmt, uint afCmd);
- /// <summary>
- ///
- /// </summary>
- /// <param name="idInst"></param>
- /// <param name="psz"></param>
- /// <param name="iCodePage"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "DdeCreateStringHandle", CharSet = CharSet.Ansi)]
- public static extern IntPtr DdeCreateStringHandle(uint idInst, string psz, int iCodePage);
- /// <summary>
- ///
- /// </summary>
- /// <param name="hConv"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "DdeDisconnect", CharSet = CharSet.Ansi)]
- public static extern bool DdeDisconnect(IntPtr hConv);
- /// <summary>
- ///
- /// </summary>
- /// <param name="idInst"></param>
- /// <param name="hConv"></param>
- /// <param name="wCmd"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "DdeEnableCallback", CharSet = CharSet.Ansi)]
- public static extern bool DdeEnableCallback(uint idInst, IntPtr hConv, uint wCmd);
- /// <summary>
- ///
- /// </summary>
- /// <param name="hData"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "DdeFreeDataHandle", CharSet = CharSet.Ansi)]
- public static extern bool DdeFreeDataHandle(IntPtr hData);
- /// <summary>
- ///
- /// </summary>
- /// <param name="idInst"></param>
- /// <param name="hsz"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "DdeFreeStringHandle", CharSet = CharSet.Ansi)]
- public static extern bool DdeFreeStringHandle(uint idInst, IntPtr hsz);
- /// <summary>
- ///
- /// </summary>
- /// <param name="hData"></param>
- /// <param name="pDst"></param>
- /// <param name="cbMax"></param>
- /// <param name="cbOff"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "DdeGetData", CharSet = CharSet.Ansi)]
- public static extern uint DdeGetData(IntPtr hData, [Out] byte[] pDst, uint cbMax, uint cbOff);
- //[DllImport("user32.dll", EntryPoint = "DdeInitialize", CharSet = CharSet.Ansi)]
- //public static extern uint DdeInitialize(ref uint pidInst, DdeDelegate pfnCallback, uint afCmd, uint ulRes);
- /// <summary>
- ///
- /// </summary>
- /// <param name="idInst"></param>
- /// <param name="hsz"></param>
- /// <param name="psz"></param>
- /// <param name="cchMax"></param>
- /// <param name="iCodePage"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "DdeQueryString", CharSet = CharSet.Ansi)]
- public static extern uint DdeQueryString(uint idInst, IntPtr hsz, StringBuilder psz, uint cchMax, int iCodePage);
- /// <summary>
- ///
- /// </summary>
- /// <param name="idInst"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "DdeUninitialize", CharSet = CharSet.Ansi)]
- public static extern bool DdeUninitialize(uint idInst);
- #endregion
- /// <summary>
- /// SetParent
- /// </summary>
- /// <param name="hWndChild"></param>
- /// <param name="hWndNewParent"></param>
- /// <returns></returns>
- [DllImport("user32.dll", SetLastError = true)]
- public static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
- /// <summary>
- /// MoveWindow
- /// </summary>
- /// <param name="hwnd"></param>
- /// <param name="x"></param>
- /// <param name="y"></param>
- /// <param name="cx"></param>
- /// <param name="cy"></param>
- /// <param name="repaint"></param>
- /// <returns></returns>
- [DllImport("user32.dll", SetLastError = true)]
- public static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);
- //bool repaint是否接受原始窗体
- /// <summary>
- /// GetSystemMenu
- /// </summary>
- /// <param name="hWnd"></param>
- /// <param name="Revert"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "GetSystemMenu")]
- public static extern Int32 GetSystemMenu(Int32 hWnd, int Revert);
- /// <summary>
- /// GetSystemMenu
- /// </summary>
- /// <param name="hWnd"></param>
- /// <param name="Revert"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "GetSystemMenu")] //第二种方法
- public static extern Int32 GetSystemMenu(Int32 hWnd, bool Revert);
- /// <summary>
- /// GetSystemMenu
- /// </summary>
- /// <param name="hwnd"></param>
- /// <param name="bRevert"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "GetSystemMenu")] //第三种方法
- public static extern IntPtr GetSystemMenu(IntPtr hwnd, int bRevert);
- /// <summary>
- /// GetMenuItemCount
- /// </summary>
- /// <param name="hMenu"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "GetMenuItemCount")]
- public static extern Int32 GetMenuItemCount(Int32 hMenu);
- /// <summary>
- /// GetMenuItemID
- /// </summary>
- /// <param name="Menuhandle"></param>
- /// <param name="pos"></param>
- /// <returns></returns>
- [DllImport("user32.dll")]
- public static extern int GetMenuItemID(int Menuhandle, int pos);
- /// <summary>
- /// RemoveMenu
- /// </summary>
- /// <param name="hMenu"></param>
- /// <param name="nPosition"></param>
- /// <param name="wFlags"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "RemoveMenu")]
- public static extern Int32 RemoveMenu(Int32 hMenu, Int32 nPosition, Int32 wFlags);
- /// <summary>
- /// DeleteMenu
- /// </summary>
- /// <param name="hMenu"></param>
- /// <param name="nPosition"></param>
- /// <param name="wFlags"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "DeleteMenu")]
- public static extern int DeleteMenu(
- IntPtr hMenu,
- int nPosition,
- int wFlags);
- /// <summary>
- /// DrawMenuBar
- /// </summary>
- /// <param name="hWnd"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "DrawMenuBar")]
- public static extern Int32 DrawMenuBar(Int32 hWnd);
- /// <summary>
- /// GetWindowThreadProcessId
- /// </summary>
- /// <param name="hWnd"></param>
- /// <param name="lpdwProcessId"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId", SetLastError = true,
- CharSet = CharSet.Unicode, ExactSpelling = true,
- CallingConvention = CallingConvention.StdCall)]
- private static extern long GetWindowThreadProcessId(long hWnd, long lpdwProcessId);
- /// <summary>
- /// FindWindow
- /// </summary>
- /// <param name="lpClassName"></param>
- /// <param name="lpWindowName"></param>
- /// <returns></returns>
- [DllImport("user32.dll", SetLastError = true)]
- private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
- /// <summary>
- /// SetWindowLong
- /// </summary>
- /// <param name="hWnd"></param>
- /// <param name="nIndex"></param>
- /// <param name="dwNewLong"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "SetWindowLongA", SetLastError = true)]
- public static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong); //第二种方法
- /// <summary>
- /// SetWindowPos
- /// </summary>
- /// <param name="hwnd"></param>
- /// <param name="hWndInsertAfter"></param>
- /// <param name="x"></param>
- /// <param name="y"></param>
- /// <param name="cx"></param>
- /// <param name="cy"></param>
- /// <param name="wFlags"></param>
- /// <returns></returns>
- [DllImport("user32.dll", SetLastError = true)]
- public static extern long SetWindowPos(IntPtr hwnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint wFlags);
- /// <summary>
- /// SetWindowPos2
- /// </summary>
- /// <param name="hWnd"></param>
- /// <param name="hWndInsertAfter"></param>
- /// <param name="X"></param>
- /// <param name="Y"></param>
- /// <param name="cx"></param>
- /// <param name="cy"></param>
- /// <param name="uFlags"></param>
- /// <returns></returns>
- [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
- public static extern bool SetWindowPos2(
- int hWnd, // handle to window
- int hWndInsertAfter, // placement-order handle
- int X, // horizontal position
- int Y, // vertical position
- int cx, // width
- int cy, // height
- uint uFlags // window-positioning options
- );
- [DllImport("user32.dll", EntryPoint = "PostMessageA", SetLastError = true)]
- private static extern bool PostMessage(IntPtr hwnd, uint Msg, long wParam, long lParam);
- /// <summary>
- /// SetWindowLong
- /// </summary>
- /// <param name="hWnd"></param>
- /// <param name="nIndex"></param>
- /// <param name="newN"></param>
- /// <returns></returns>
- [DllImport("user32.dll")]
- public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int newN);
- /// <summary>
- /// GetWindowLong
- /// </summary>
- /// <param name="hWnd"></param>
- /// <param name="nIndex"></param>
- /// <returns></returns>
- [DllImport("user32.dll")]
- public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
- #endregion
- //******************************************************
- #region 定义 常量
- /// <summary>
- ///
- /// </summary>
- public const int GWL_STYLE = -16; //设置新的窗口风格
- /// <summary>
- ///
- /// </summary>
- public const int GWL_EXSTYLE = -20;
- /// <summary>
- ///
- /// </summary>
- public const int WS_CAPTION = 0x00C00000; //WS_CAPTION = WS_BORDER | WS_DLGFRAME; //window with a title bar
- /// <summary>
- ///
- /// </summary>
- public const int WS_SYSMENU = 0x00080000;
- /// <summary>
- ///
- /// </summary>
- public const int MF_BYCOMMAND = 0x0;
- /// <summary>
- ///
- /// </summary>
- public const int WS_VISIBLE = 0x10000000;
- /// <summary>
- ///
- /// </summary>
- public const int HWND_NOTOPMOST = -2;
- /// <summary>
- ///
- /// </summary>
- public const int MF_BYPOSITION = 0x400;
- /// <summary>
- ///
- /// </summary>
- public const int MF_REMOVE = 0x1000;
- /// <summary>
- ///
- /// </summary>
- public const int WS_MAXIMIZEBOX = 0x00010000; //
- /// <summary>
- ///
- /// </summary>
- public const int WS_MINIMIZEBOX = 0x00020000; //
- /// <summary>
- ///
- /// </summary>
- public const int SWP_DRAWFRAME = 0x20;
- /// <summary>
- ///
- /// </summary>
- public const int SWP_NOOWNERZORDER = 0x200; // Dont do owner Z ordering
- /// <summary>
- ///
- /// </summary>
- public const int SWP_NOREDRAW = 0x8; //
- /// <summary>
- ///
- /// </summary>
- public const int SWP_NOZORDER = 0x4; //
- /// <summary>
- ///
- /// </summary>
- public const int SWP_SHOWWINDOW = 0x0040;
- /// <summary>
- ///
- /// </summary>
- public const int SWP_HIDEWINDOW = 0x0080;
- /// <summary>
- ///
- /// </summary>
- public const int SWP_FRAMECHANGED = 0x20; //H20 The frame changed: send WM_NCCALCSIZE
- /// <summary>
- ///
- /// </summary>
- public const int SWP_NOACTIVATE = 0x10;
- /// <summary>
- ///
- /// </summary>
- public const int SWP_ASYNCWINDOWPOS = 0x4000;
- /// <summary>
- ///
- /// </summary>
- public const int SWP_NOMOVE = 0x2; //H2
- /// <summary>
- ///
- /// </summary>
- public const int SWP_NOSIZE = 0x1; //H1
- /// <summary>
- ///
- /// </summary>
- public const int SWP_NOCOPYBITS = 0x100;
- /// <summary>
- ///
- /// </summary>
- public const int SWP_NOREPOSITION = SWP_NOOWNERZORDER;
- /// <summary>
- ///
- /// </summary>
- public const int WM_CLOSE = 0x10;
- /// <summary>
- ///
- /// </summary>
- public const int WS_CHILD = 0x40000000;
- /// <summary>
- ///
- /// </summary>
- public const int WS_BORDER = 0x00800000; //window with border
- /// <summary>
- ///
- /// </summary>
- public const int WS_DLGFRAME = 0x00400000; //window with double border but no title
- // Extended Window Styles
- /// <summary>
- ///
- /// </summary>
- public static int WS_EX_MDICHILD = 0x40;
- /// <summary>
- ///
- /// </summary>
- public static int WS_EX_TOPMOST = 0x00000008;
- /// <summary>
- ///
- /// </summary>
- public static int WS_EX_TRANSPARENT = 0x00000020;
- /// <summary>
- ///
- /// </summary>
- public static int WS_EX_TOOLWINDOW = 0x00000080;
- /// <summary>
- ///
- /// </summary>
- public static int WS_EX_WINDOWEDGE = 0x00000100;
- /// <summary>
- ///
- /// </summary>
- public static int WS_EX_CLIENTEDGE = 0x00000200;
- /// <summary>
- ///
- /// </summary>
- public const int SW_HIDE = 0;
- /// <summary>
- ///
- /// </summary>
- public const int SW_SHOWNORMAL = 1;
- /// <summary>
- ///
- /// </summary>
- public const int SW_SHOWMINIMIZED = 2;
- /// <summary>
- ///
- /// </summary>
- public const int SW_SHOWMAXIMIZED = 3;
- /// <summary>
- ///
- /// </summary>
- public const int SW_SHOWNOACTIVATE = 4;
- /// <summary>
- ///
- /// </summary>
- public const int SW_RESTORE = 9;
- /// <summary>
- ///
- /// </summary>
- public const int SW_SHOWDEFAULT = 10;
- #endregion
- }
- #endregion
- #region 静态类)DataTable导出到Excel文件
- /// <summary>
- /// (静态类)DataTable导出到Excel文件
- /// </summary>
- public class ExportToExcel
- {
- /// <summary>
- /// 把DataTable的数据导出到Excel文件中
- /// </summary>
- /// <param name="_dataTable">要导出的数据表</param>
- /// <param name="_fileName">保存的Excel文件名</param>
- /// <returns>是否导出成功</returns>
- public static string dataTableExportToExcel_cell(ref DataTable _dataTable, string _fileName)
- {
- if (_dataTable == null) { return null; }
- SuperTools.UC_EmbedExcelIntoWinFormNoDLL uc1 = new UC_EmbedExcelIntoWinFormNoDLL();
- uc1.AppExcel_Open(null, false);
- string strErr = null;
- try
- {
- //写入字段名的信息
- for (int i = 0; i < _dataTable.Columns.Count; i++)
- {
- uc1.SetCell_Value(1, i + 1, _dataTable.Columns[i].Caption); //写第一行内容为dataTable的字段名
- }
- //写入表中数据内容
- for (int i = 0; i < _dataTable.DefaultView.Count; i++)
- {
- for (int col = 0; col < _dataTable.Columns.Count; col++)
- {
- uc1.SetCell_Value(i + 2, col + 1, _dataTable.DefaultView[i][col].ToString()); //转化为文本再写到excel当中
- }
- }
- //uc1.App_ExcelSave(_fileName);
- strErr = null;
- }
- catch (Exception operExce)
- {
- strErr = "写入表中数据!错误原因:" + operExce.Message;
- }
- finally
- {
- uc1.AppExcel_Exit();
- }
- return strErr;
- }
- /// <summary>
- /// 把DataTable的数据导出到Excel文件中
- /// </summary>
- /// <param name="_dataTable">要导出的数据表</param>
- /// <param name="_fileName">保存的Excel文件名</param>
- /// <returns>是否导出成功</returns>
- public static string dataTableExportToExcel_Range(ref DataTable _dataTable, string _fileName)
- {
- if (_dataTable == null) { return null; }
- SuperTools.UC_EmbedExcelIntoWinFormNoDLL uc1 = new UC_EmbedExcelIntoWinFormNoDLL();
- uc1.AppExcel_Open(null, false);
- string strErr = null;
- try
- {
- #region //写入字段名的信息
- ////获取A1单元格所在区域
- string BeginPoint = "A1";
- string EndPoint = Convert.ToString(Convert.ToChar(64 + _dataTable.Columns.Count)) + "1";
- int rows = 1;
- int columns = _dataTable.Columns.Count;
- string[,] Array_strHeadName_Value = new string[rows, columns]; //赋值:数值类型=string
- for (int i = 0; i < rows; i++) //第一行
- {
- for (int j = 0; j < columns; j++)
- {
- Array_strHeadName_Value[i, j] = _dataTable.Columns[j].Caption; //字段名
- }
- }
- uc1.SetRangeArray_Value(BeginPoint, EndPoint, Array_strHeadName_Value);
- #endregion
- //**********************************
- #region 写入表中数据内容 //excel的其他行的Range中填充数据
- string BeginPoint_1 = "A2";
- string EndPoint_1 = Convert.ToString(Convert.ToChar(64 + _dataTable.Columns.Count)) + (_dataTable.Rows.Count + 1).ToString().Trim();
- int rows_1 = _dataTable.Rows.Count;
- int columns_1 = _dataTable.Columns.Count;
- string[,] Array_string_Value = new string[rows_1, columns_1]; //赋值:数值类型=string
- for (int y = 0; y < _dataTable.Rows.Count; y++)
- {
- for (int x = 0; x < _dataTable.Columns.Count; x++)
- {
- Array_string_Value[y, x] = _dataTable.Rows[y][x].ToString();
- }
- }
- uc1.SetRangeArray_Value(BeginPoint_1, EndPoint_1, Array_string_Value);
- #endregion
- uc1.AppExcel_SaveAs(_fileName);
- strErr = null;
- }
- catch (Exception operExce)
- {
- strErr = "写入表中数据!错误原因:" + operExce.Message;
- }
- finally
- {
- uc1.AppExcel_Exit();
- }
- return strErr;
- }
- /// <summary>
- /// 把DataTable的数据导出到Excel文件中 测试
- /// </summary>
- /// <param name="w2"></param>
- /// <param name="fileName"></param>
- /// <returns></returns>
- public static string dataTableExportToExcel_Range_x(DataTable w2, string fileName)
- {
- object MyApp;
- object MyBook;
- object MyBooks;
- object MySheet;
- object MySheets;
- object MyRange;
- object[] MyParameters;
- //Type MyClassType;
- if (w2 == null || w2.Rows.Count == 0)
- {
- string strErr = "dataTable为空 或 dataTable表中无数据";
- return strErr;
- }
- try
- {
- // 获取Excel类型并建立其实例
- Type MyClassType = Type.GetTypeFromProgID("Excel.Application");
- if (MyClassType == null)
- {
- string strErr = "本计算机无Excel.Application";
- return strErr;
- }
- MyApp = Activator.CreateInstance(MyClassType);
- if (MyApp == null)
- {
- string strErr = "本计算机的Excel.Application无法正常使用!";
- return strErr;
- }
- //获取Workbook集
- MyBooks = MyApp.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, MyApp, null);
- //添加一个新的Workbook
- MyBook = MyBooks.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, MyBooks, null);
- //获取Sheet集
- MySheets = MyBook.GetType().InvokeMember("Worksheets", BindingFlags.GetProperty, null, MyBook, null);
- //获取第一个Sheet对象
- MyParameters = new Object[1] { 1 };
- MySheet = MySheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, MySheets, MyParameters);
- try
- {
- #region //写入字段名的信息
- ////获取A1单元格所在区域
- MyParameters = new object[1];
- MyParameters[0] = "A1:" + Convert.ToString(Convert.ToChar(64 + w2.Columns.Count)) + "1"; //定义excel的第一行的Range
- MyRange = MySheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, MySheet, MyParameters); //
- //**********************************
- //excel的第一行的Range中填充数据,该数据=dataTable的字段名
- object[] objHeaders = new Object[w2.Columns.Count];
- MyParameters = new object[1];
- // objHeaders[0] = w2.Columns[1].ToString();
- for (int i = 0; i < w2.Columns.Count; i++)
- {
- //objHeaders[i] = w2.Columns[i].ToString(); //字段名
- objHeaders[i] = w2.Columns[i].Caption; //字段名
- }
- MyParameters[0] = objHeaders;
- MyRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, MyRange, MyParameters);//写字段名
- #endregion
- //**********************************
- #region 写入表中数据内容
- //excel的其他行的Range中填充数据
- MyParameters = new object[2];
- MyParameters[0] = "A2:" + Convert.ToString(Convert.ToChar(64 + w2.Columns.Count)) + (w2.Rows.Count + 1).ToString().Trim();
- MyParameters[1] = Missing.Value;
- MyRange = MySheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, MySheet, MyParameters);
- Object[,] MyData = new Object[w2.Rows.Count, w2.Columns.Count];
- for (int y = 0; y < w2.Rows.Count; y++)
- {
- for (int x = 0; x < w2.Columns.Count; x++)
- {
- if (true) //(A3.Contains(ii))
- {
- MyData[y, x] = w2.Rows[y][x];
- }
- //else
- //{
- // MyData[ll, ii] = "'" + w2.Rows[ll][ii].ToString();
- //}
- }
- }
- MyParameters = new object[1];
- MyParameters[0] = MyData;
- MyRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, MyRange, MyParameters);
- #endregion
- ////MyParameters = new object[1];
- //////启动 Excel
- ////MyParameters[0] = true;
- ////MyApp.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, MyApp, MyParameters);
- ////MyApp.GetType().InvokeMember("UserControl", BindingFlags.SetProperty, null, MyApp, MyParameters);
- }
- catch (Exception ex)
- {
- string strErr = "操作App内容出错!错误原因:" + ex.Message;
- return strErr;
- }
- finally
- {
- //不提示保存
- MyParameters = new Object[1] { false };
- MyApp.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, MyApp, MyParameters);
- //保存文件并退出
- MyParameters = new Object[1] { fileName };
- MyBook.GetType().InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, MyBook, MyParameters);
- MyApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, MyApp, null);
- //System.Runtime.InteropServices.Marshal.ReleaseComObject(objCells);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(MySheet);
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(MySheets);
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(MyBook);
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(MyBooks);
- GC.GetTotalMemory(true);
- System.Runtime.InteropServices.Marshal.ReleaseComObject(MyApp);
- GC.GetTotalMemory(true);
- }
- return null;
- }
- catch (Exception appExce)
- {
- string strErr = "操作App出错!错误原因:" + appExce.Message;
- return strErr;
- }
- }
- /// <summary>
- /// 另外一种方法:把DataTable的数据导出到XML/Excel文件中 带格式
- /// </summary>
- /// <param name="_DataTable"></param>
- /// <param name="fileName"></param>
- public static void dataTableExportToExcelXml(DataTable _DataTable, string fileName)
- {
- System.IO.StreamWriter excelDoc;
- excelDoc = new System.IO.StreamWriter(fileName);
- const string startExcelXML = "<xml version>\r\n<Workbook " +
- "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
- " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
- "xmlns:x=\"urn:schemas- microsoft-com:office:" +
- "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
- "office:spreadsheet\">\r\n <Styles>\r\n " +
- "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
- "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
- "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
- "\r\n <Protection/>\r\n </Style>\r\n " +
- "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
- "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
- "<Style ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
- " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
- "ss:ID=\"Decimal\">\r\n <NumberFormat " +
- "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
- "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
- "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
- "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
- "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
- "</Styles>\r\n ";
- const string endExcelXML = "</Workbook>";
- int rowCount = 0;
- int sheetCount = 1;
- /*
- <xml version>
- <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
- xmlns:o="urn:schemas-microsoft-com:office:office"
- xmlns:x="urn:schemas-microsoft-com:office:excel"
- xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
- <Styles>
- <Style ss:ID="Default" ss:Name="Normal">
- <Alignment ss:Vertical="Bottom"/>
- <Borders/>
- <Font/>
- <Interior/>
- <NumberFormat/>
- <Protection/>
- </Style>
- <Style ss:ID="BoldColumn">
- <Font x:Family="Swiss" ss:Bold="1"/>
- </Style>
- <Style ss:ID="StringLiteral">
- <NumberFormat ss:Format="@"/>
- </Style>
- <Style ss:ID="Decimal">
- <NumberFormat ss:Format="0.0000"/>
- </Style>
- <Style ss:ID="Integer">
- <NumberFormat ss:Format="0"/>
- </Style>
- <Style ss:ID="DateLiteral">
- <NumberFormat ss:Format="mm/dd/yyyy;@"/>
- </Style>
- </Styles>
- <Worksheet ss:Name="Sheet1">
- </Worksheet>
- </Workbook>
- */
- excelDoc.Write(startExcelXML);
- excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
- excelDoc.Write("<Table>");
- excelDoc.Write("<Row>");
- for (int x = 0; x < _DataTable.Columns.Count; x++)
- {
- excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
- excelDoc.Write(_DataTable.Columns[x].ColumnName);
- excelDoc.Write("</Data></Cell>");
- }
- excelDoc.Write("</Row>");
- foreach (DataRow x in _DataTable.Rows)
- {
- rowCount++;
- //if the number of rows is > 64000 create a new page to continue output
- if (rowCount == 64000)
- {
- rowCount = 0;
- sheetCount++;
- excelDoc.Write("</Table>");
- excelDoc.Write(" </Worksheet>");
- excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
- excelDoc.Write("<Table>");
- }
- excelDoc.Write("<Row>"); //ID=" + rowCount + "
- for (int y = 0; y < _DataTable.Columns.Count; y++)
- {
- System.Type rowType;
- rowType = x[y].GetType();
- switch (rowType.ToString())
- {
- case "System.String":
- string XMLstring = x[y].ToString();
- XMLstring = XMLstring.Trim();
- XMLstring = XMLstring.Replace("&", "&");
- XMLstring = XMLstring.Replace(">", ">");
- XMLstring = XMLstring.Replace("<", "<");
- excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
- "<Data ss:Type=\"String\">");
- excelDoc.Write(XMLstring);
- excelDoc.Write("</Data></Cell>");
- break;
- case "System.DateTime":
- //Excel has a specific Date Format of YYYY-MM-DD followed by
- //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
- //The Following Code puts the date stored in XMLDate
- //to the format above
- DateTime XMLDate = (DateTime)x[y];
- string XMLDatetoString = ""; //Excel Converted Date
- XMLDatetoString = XMLDate.Year.ToString() +
- "-" +
- (XMLDate.Month < 10 ? "0" +
- XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
- "-" +
- (XMLDate.Day < 10 ? "0" +
- XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
- "T" +
- (XMLDate.Hour < 10 ? "0" +
- XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
- ":" +
- (XMLDate.Minute < 10 ? "0" +
- XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
- ":" +
- (XMLDate.Second < 10 ? "0" +
- XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
- ".000";
- excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
- "<Data ss:Type=\"DateTime\">");
- excelDoc.Write(XMLDatetoString);
- excelDoc.Write("</Data></Cell>");
- break;
- case "System.Boolean":
- excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
- "<Data ss:Type=\"String\">");
- excelDoc.Write(x[y].ToString());
- excelDoc.Write("</Data></Cell>");
- break;
- case "System.Int16":
- case "System.Int32":
- case "System.Int64":
- case "System.Byte":
- excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
- "<Data ss:Type=\"Number\">");
- excelDoc.Write(x[y].ToString());
- excelDoc.Write("</Data></Cell>");
- break;
- case "System.Decimal":
- case "System.Double":
- excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
- "<Data ss:Type=\"Number\">");
- excelDoc.Write(x[y].ToString());
- excelDoc.Write("</Data></Cell>");
- break;
- case "System.DBNull":
- excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
- "<Data ss:Type=\"String\">");
- excelDoc.Write("");
- excelDoc.Write("</Data></Cell>");
- break;
- default:
- throw (new Exception(rowType.ToString() + " not handled."));
- }
- }
- excelDoc.Write("</Row>");
- }
- excelDoc.Write("</Table>");
- excelDoc.Write(" </Worksheet>");
- excelDoc.Write(endExcelXML);
- excelDoc.Close();
- }
- }
- #endregion
- #region (静态类)DataTable的工具类
- /// <summary>
- /// (静态类)DataTable的工具类
- /// </summary>
- public class DataTableTools
- {
- /// <summary>
- /// Hashtable的排序
- /// </summary>
- /// <param name="_HasTable">Hashtable的名字</param>
- /// <returns> System.Collections.ArrayList</returns>
- public static System.Collections.ArrayList HashTable_To_Sort(System.Collections.Hashtable _HasTable)
- {
- //根据选择的行的ID号,读取其相应的数据
- System.Collections.ArrayList akeys = new System.Collections.ArrayList(_HasTable.Keys);
- akeys.Sort(); //按键值字母顺序进行排序
- foreach (int str_skey in akeys)
- {
- Console.Write(str_skey + ":");
- Console.WriteLine(_HasTable[str_skey]);//排序后输出
- }
- return akeys;
- }
- /// <summary>
- /// 将目标Hashtable转换成DataTable返回
- /// </summary>
- /// <param name="HasTable">目标Hashtable</param>
- /// <returns>转换后的DataTable</returns>
- public static DataTable HashTable_To_Table(System.Collections.Hashtable HasTable)
- {
- try
- {
- DataTable rtn_Table = new DataTable("HASHTABLE");
- DataColumn KeyColumn = new DataColumn("KEY", typeof(object));
- DataColumn ValueColumn = new DataColumn("VALUE", typeof(object));
- rtn_Table.Columns.Add(KeyColumn);
- rtn_Table.Columns.Add(ValueColumn);
- rtn_Table.AcceptChanges();
- System.Collections.IDictionaryEnumerator Has = HasTable.GetEnumerator();
- while (Has.MoveNext())
- {
- DataRow nRow = rtn_Table.NewRow();
- nRow["KEY"] = Has.Key;
- nRow["VALUE"] = Has.Value;
- rtn_Table.Rows.Add(nRow);
- }
- rtn_Table.AcceptChanges();
- return rtn_Table;
- }
- catch (System.Exception ex)
- {
- Console.WriteLine(ex.ToString());
- return null;
- }
- }
- /// <summary>
- /// Hashtable按键值字母顺序进行排序
- /// </summary>
- /// <param name="_ht_1"></param>
- /// <returns></returns>
- public static DataTable SetHashtablekeysSort(System.Collections.Hashtable _ht_1)
- {
- DataTable myDataTable = new DataTable();
- //*********************
- System.Collections.ArrayList akeys = new System.Collections.ArrayList(_ht_1.Keys); //别忘了导入System.Collections
- akeys.Sort(); //按键值字母顺序进行排序
- //*****************************************
- myDataTable = SuperTools.DataTableTools.HashTable_To_Table(_ht_1);
- return myDataTable;
- }
- /// <summary>
- /// 将目标DataTable 转换成Hashtable返回
- /// </summary>
- /// <param name="_DataTable">目标Hashtable</param>
- /// <returns>转换后的Hashtable</returns>
- public static System.Collections.Hashtable Table_To_HashTable(DataTable _DataTable)
- {
- System.Collections.Hashtable _Hashtable = null;
- return _Hashtable;
- }
- ///// <summary>
- ///// 动态更新标的行数,根据新的行数动态更新
- ///// </summary>
- ///// <param name="table">目标DataTable</param>
- ///// <param name="newRowCount">新的行数</param>
- //public static void SetTableRows(ref DataTable table, int newRowCount)
- //{
- // int oldRowCount = table.Rows.Count;
- // if (oldRowCount != newRowCount)
- // {
- // int absCount = Math.Abs(oldRowCount - newRowCount);
- // if (oldRowCount > newRowCount)
- // {
- // for (int i = oldRowCount - 1; i >= absCount; i--)
- // {
- // table.Rows[i].Delete();
- // }
- // }
- // else
- // {
- // object[] ColumnValue = new object[table.Columns.Count];
- // for (int i = 0; i < absCount; i++)
- // {
- // table.Rows.Add(ColumnValue);
- // }
- // }
- // }
- //}
- /// <summary>
- /// 定义的table列的一个示例
- /// </summary>
- public static void Add_Columns_EG()
- {
- System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
- ParaColumns.Add("ID|Int16"); //
- ParaColumns.Add("日期|DateTime"); // System.DateTime
- ParaColumns.Add("工资|Decimal"); //System.Decimal
- ParaColumns.Add("电话|String"); //System.String
- ParaColumns.Add("年龄|Int16"); //System.Int16
- ParaColumns.Add("选择|Boolean"); //System .Boolean
- System.Data.DataTable MyDataDataTable = new DataTable();
- Add_Columns(ref MyDataDataTable, ParaColumns);
- }
- /// <summary>
- /// 定义的table列
- /// </summary>
- /// <param name="_Table">目标DataTable</param>
- /// <param name="_ParaColumns">增加的数列</param>
- public static void Add_Columns(ref System.Data.DataTable _Table, System.Collections.ArrayList _ParaColumns)
- {
- for (int i = 0; i < _ParaColumns.Count; i++)
- {
- string[] strColumnsNameType = new string[2]; //字段名和字段类型
- strColumnsNameType = ((string)_ParaColumns[i]).Split('|');
- string strColumnsType = strColumnsNameType[1];
- #region 设置字段名字和类型
- System.Type MyType;
- switch (strColumnsType)
- {
- //ParaColumns.Add("ID|Int16"); //
- //ParaColumns.Add("日期|DateTime"); // System.DateTime
- //ParaColumns.Add("工资|Decimal"); //System.Decimal
- //ParaColumns.Add("电话|String"); //System.String
- //ParaColumns.Add("年龄|Int16"); //System.Int16
- //ParaColumns.Add("选择|Boolean"); //System .Boolean
- case "String":
- MyType = typeof(System.String);
- break;
- case "Boolean":
- MyType = typeof(System.Boolean);
- break;
- case "Int16":
- MyType = typeof(System.Int16);
- break;
- case "Decimal":
- MyType = typeof(System.Decimal);
- break;
- case "DateTime":
- MyType = typeof(System.DateTime);
- break;
- }
- MyType = typeof(string);
- #endregion 设置字段名字和类型
- _Table.Columns.Add(strColumnsNameType[0], MyType);
- //typeof(string);
- //typeof(decimal);
- //typeof(float);
- //typeof(bool);
- //typeof(byte);
- //typeof(Double);
- //typeof(System.String);
- }
- }
- /// <summary>
- /// 增加的table行
- /// </summary>
- /// <param name="_Table">目标DataTable</param>
- /// <param name="_RowsCount">DataTable的行数</param>
- public static void Add_Rows(ref System.Data.DataTable _Table, int _RowsCount)
- {
- //for (int i = 0; i < _IPCount; i++)
- //{
- // _Table.Rows.Add(new object[] { null, null, null, null, null, null, null, null, null, null, null });
- //}
- //**********
- int oldRowCount = _Table.Rows.Count;
- int NewRowCount = _RowsCount;
- if (oldRowCount != NewRowCount)
- {
- int absCount = Math.Abs(oldRowCount - NewRowCount);
- if (oldRowCount > NewRowCount)
- {
- for (int i = oldRowCount - 1; i >= absCount; i--)
- {
- _Table.Rows[i].Delete();
- }
- }
- else
- {
- object[] ColumnValue = new object[_Table.Columns.Count];
- for (int i = 0; i < absCount; i++)
- {
- _Table.Rows.Add(ColumnValue);
- } //for
- } //else
- } //if
- }
- /// <summary>
- /// 增加_Table行的一个实际示例(五种数据类型)
- /// </summary>
- /// <param name="_Table">目标DataTable</param>
- /// <param name="_RowsCount">DataTable的行数</param>
- public static void Add_Rows_EG(ref System.Data.DataTable _Table, int _RowsCount)
- {
- Random r = new Random();
- object[] ColumnValue = new object[_Table.Columns.Count];
- DateTime t = DateTime.Now; //取得当前系统时间
- TimeSpan MySpan = new TimeSpan(1, 2, 3, 4); // 注意: TimeSpan(days, hours, minutes, seconds)
- //t = t.Subtract(MySpan); //在当前时间上减上MySpan string ss = "2007-9-5 20:33:49";
- for (int i = 0; i < _RowsCount; i++)
- {
- ColumnValue[0] = i;
- ColumnValue[1] = t;
- ColumnValue[2] = r.NextDouble() * 1000000;
- ColumnValue[3] = RandomTelephone(r);
- ColumnValue[4] = r.Next(100);
- ColumnValue[5] = false;
- _Table.Rows.Add(ColumnValue);
- t = t.Add(MySpan); //在当前时间上加上上MySpan
- //ColumnValue["ID"] = i;
- //ColumnValue["日期"] = DateTime.Today.AddDays(i);
- //ColumnValue["工资"] = r.NextDouble() * 1000000;
- //ColumnValue["电话"] = RandomTelephone(r);
- //ColumnValue["年龄"] = r.Next(100);
- //ColumnValue["选择"] = false;
- }
- }
- ///// <summary>
- ///// 增加_Table行的一个实际示例(五种数据类型)
- ///// </summary>
- ///// <param name="_ObjectArray">待写入的值</param>
- ///// <param name="_RowsCount">DataTable的行数</param>
- /////
- /// <summary>
- /// 根据一个已有的空二维数组的 Object[,] ,填充随机数
- /// </summary>
- /// <param name="_ObjectArray">待写入已有的二维数组的Object[,]</param>
- /// <returns>填充随机数的二维数组的 Object[,]</returns>
- public static object[,] Get_ObjectArrayValue_Random(ref Object[,] _ObjectArray)
- {
- Random r = new Random();
- DateTime t = DateTime.Now; //取得当前系统时间
- TimeSpan MySpan = new TimeSpan(1, 2, 3, 4); // 注意: TimeSpan(days, hours, minutes, seconds)
- //t = t.Subtract(MySpan); //在当前时间上减上MySpan string ss = "2007-9-5 20:33:49";
- for (int i = 0; i < _ObjectArray.GetLength(0); i++) //行数
- {
- if (_ObjectArray.GetLength(1) >= 5)
- {
- _ObjectArray[i, 0] = i;
- _ObjectArray[i, 1] = t;
- _ObjectArray[i, 2] = r.NextDouble() * 1000000;
- _ObjectArray[i, 3] = RandomTelephone(r);
- _ObjectArray[i, 4] = r.Next(100);
- _ObjectArray[i, 5] = false;
- t = t.Add(MySpan); //在当前时间上加上上MySpan
- }
- }
- return _ObjectArray;
- }
- /// <summary>
- /// 根据行列数得到填充随机数的二维数组的 Object[,]
- /// </summary>
- /// <param name="_nRowsCount">行数</param>
- /// <param name="_nColumnsCount">列数</param>
- /// <returns>填充随机数的二维数组的 Object[,]</returns>
- public static object[,] Get_ObjectArrayValue_EG(int _nRowsCount, int _nColumnsCount)
- {
- Random r = new Random();
- object[,] obEG = new object[_nRowsCount, _nColumnsCount];
- obEG = SuperTools.DataTableTools.Get_ObjectArrayValue_Random(ref obEG);
- return obEG;
- }
- /// <summary>
- /// 产生一个随机的字符
- /// </summary>
- /// <param name="r"></param>
- /// <returns></returns>
- private static string RandomTelephone(Random r)
- {
- //Random r = new Random();
- System.Text.StringBuilder s = new System.Text.StringBuilder();
- for (int i = 0; i < 11; i++)
- s.Append(r.Next(10));
- return s.ToString();
- }
- /// <summary>
- /// 二维数组的 Object[,]转换成为DataTable 字段类型都为string
- /// </summary>
- /// <param name="_ObjectArray">二维数组的 Object[,]</param>
- /// <param name="_bExistColumnsName">二维数组的 Object[,]是否包含字段名</param>
- /// <returns></returns>
- public static DataTable Get_DataTableFromObjectArray(ref Object[,] _ObjectArray, bool _bExistColumnsName)
- {
- DataTable dtTable1 = new DataTable();
- if (_ObjectArray == null) { return null; }
- if (!_bExistColumnsName)
- {
- System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
- for (int i = 0; i < _ObjectArray.GetLength(1); i++) //列数
- {
- ParaColumns.Add("字段" + (i + 1).ToString() + "|String"); //System.String
- }
- Add_Columns(ref dtTable1, ParaColumns); //增加DataTabe列
- Add_Rows(ref dtTable1, _ObjectArray.GetLength(0)); //:增加DataTabe行
- for (int i = 0; i < _ObjectArray.GetLength(0); i++) //行数
- {
- for (int j = 0; j < _ObjectArray.GetLength(1); j++) //列数
- {
- dtTable1.Rows[i][j] = _ObjectArray[i, j];
- }
- }
- }
- else
- {
- System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
- for (int i = 0; i < _ObjectArray.GetLength(1); i++) //列数
- {
- ParaColumns.Add(_ObjectArray[1, i].ToString() + "|String"); //System.String
- }
- Add_Columns(ref dtTable1, ParaColumns); //增加DataTabe列
- Add_Rows(ref dtTable1, _ObjectArray.GetLength(0) - 1); //:增加DataTabe行
- for (int i = 0; i < _ObjectArray.GetLength(0); i++) //行数
- {
- for (int j = 0; j < _ObjectArray.GetLength(1); j++) //列数
- {
- dtTable1.Rows[i][j] = _ObjectArray[i, j];
- }
- }
- }
- return dtTable1;
- }
- /// <summary>
- /// 设置字段名字和类型 并且初始化行数,内容为空
- /// </summary>
- /// <param name="_Table">目标DataTable</param>
- /// <param name="_ParaColumns">增加空内容到每一行</param>
- ///<param name="_RowsCount">增加空内容到每一行</param>
- public static void Set_Table_Columns_Rows(ref System.Data.DataTable _Table, System.Collections.ArrayList _ParaColumns, int _RowsCount)
- {
- Add_Columns(ref _Table, _ParaColumns);
- Add_Rows(ref _Table, _RowsCount);
- }
- /// <summary>
- /// 根据查询条件:刷选行(满足条件的行),返回新的DataTable
- /// </summary>
- /// <param name="_dt">源数据DataTable</param>
- /// <param name="_strSelectRowsCondition">选择列的条件:刷选行(满足条件的行)</param>
- /// <returns></returns>
- public static DataTable GetNewDataTable(ref DataTable _dt, string _strSelectRowsCondition)
- {
- if (_dt == null)
- {
- return null;
- }
- //string strMyFilterCondition = "蒸汽";
- //string Filter = "介质类型 = '" + strMyFilterCondition + "'"; //介质类型过滤
- DataTable newdt = new DataTable();
- newdt = _dt.Clone(); //创建同结构的表,但没有行数据 行数= 0;
- try
- {
- DataRow[] rows = _dt.Select(_strSelectRowsCondition);
- //DataRow[] rows = _dt.Select(_strCondition);
- //for (int i = 0; i < rows.Length; i++)
- //{
- // newdt.ImportRow((DataRow)rows[i]);
- //}
- foreach (DataRow row in rows)
- {
- //newdt.Rows.Add(row.ItemArray); //ok
- newdt.ImportRow(row); //ok
- }
- newdt.AcceptChanges();
- }
- catch //(Exception ex)
- {
- return null;
- }
- return newdt;//返回的查询结果
- }
- /// <summary>
- /// 根据给定的列名,返回新的DataTable
- /// </summary>
- /// <param name="_dt">源数据DataTable</param>
- /// <param name="_Column_1_Name">第一列的列名</param>
- /// <param name="_Column_2_Name">第二列的列名</param>
- /// <returns></returns>
- public static DataTable GetNewDataTable(ref DataTable _dt, string _Column_1_Name, string _Column_2_Name)
- {
- if (_dt == null)
- {
- return null;
- }
- DataTable newdt = new DataTable();
- System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
- if (_dt.Columns.Contains(_Column_1_Name))
- {
- string clName = _Column_1_Name;
- System.Type clType = _dt.Columns[_Column_1_Name].DataType; //可能有问题
- newdt.Columns.Add(clName, clType); //增加列
- }
- if (_dt.Columns.Contains(_Column_2_Name))
- {
- string clName = _Column_2_Name;
- System.Type clType = _dt.Columns[_Column_2_Name].DataType;
- newdt.Columns.Add(clName, clType); //增加列
- }
- Add_Rows(ref newdt, _dt.Rows.Count); //增加空行
- //for (int i = 0; i < _dt.Rows.Count; i++)
- //{
- // newdt.Rows[i][_Column_1_Name] = _dt.Rows[i][_Column_1_Name];
- // newdt.Rows[i][_Column_2_Name] = _dt.Rows[i][_Column_2_Name];
- //}
- for (int i = 0; i < _dt.Rows.Count; i++)
- {
- foreach (DataColumn NewColumn in newdt.Columns) ////新表中的每列
- {
- newdt.Rows[i][NewColumn.ColumnName] = _dt.Rows[i][NewColumn.ColumnName];
- }
- }
- newdt.AcceptChanges();
- return newdt;//返回的查询结果
- }
- /// <summary>
- /// 根据给定的列名(数组),返回新的DataTable
- /// </summary>
- /// <param name="_dt">源数据DataTable</param>
- /// <param name="ColumnsName">列名的数组</param>
- /// <returns></returns>
- public static DataTable GetNewDataTable(ref DataTable _dt, string[] ColumnsName)
- {
- if (_dt == null)
- {
- return null;
- }
- DataTable newdt = new DataTable();
- System.Collections.ArrayList ParaColumns = new System.Collections.ArrayList();
- for (int i = 0; i < ColumnsName.Length; i++)
- {
- string clName = ColumnsName[i];
- System.Type clType = _dt.Columns[ColumnsName[i]].DataType; //可能有问题
- newdt.Columns.Add(clName, clType); //增加列
- }
- Add_Rows(ref newdt, _dt.Rows.Count); //增加空行
- //for (int i = 0; i < _dt.Rows.Count; i++)
- //{
- // newdt.Rows[i][_Column_1_Name] = _dt.Rows[i][_Column_1_Name];
- // newdt.Rows[i][_Column_2_Name] = _dt.Rows[i][_Column_2_Name];
- //}
- for (int i = 0; i < _dt.Rows.Count; i++)
- {
- foreach (DataColumn NewColumn in newdt.Columns) ////新表中的每列
- {
- newdt.Rows[i][NewColumn.ColumnName] = _dt.Rows[i][NewColumn.ColumnName];
- }
- }
- newdt.AcceptChanges();
- return newdt;//返回的查询结果
- }
- /// <summary>
- /// 复制数据,深度复制
- /// </summary>
- /// <param name="dataSourceRow">数据源,待复制的数据</param>
- /// <param name="dataStruct">数据结构/表结构</param>
- /// <returns>处理后的DataTable</returns>
- public static DataTable CopyData(DataRow[] dataSourceRow, DataTable dataStruct)
- {
- DataTable dataTable = new DataTable();
- //定义表结构
- DataColumn col;
- foreach (DataColumn column in dataStruct.Columns)
- {
- col = new DataColumn();
- col.ColumnName = column.ColumnName;
- col.DataType = column.DataType;
- //add column
- dataTable.Columns.Add(col);
- }
- foreach (DataRow row in dataSourceRow)
- {
- DataRow tempRow = dataTable.NewRow();
- foreach (DataColumn column in dataStruct.Columns)
- {
- try
- {
- tempRow[column.ColumnName] = row[column.ColumnName];
- }
- catch
- { continue; }
- }
- dataTable.Rows.Add(tempRow);
- }
- return dataTable;
- }
- }
- #endregion
- #region (静态类)操作文件的工具
- /// <summary>
- /// (静态类)操作文件的工具
- /// </summary>
- public class FileTools
- {
- /// <summary>
- /// 列举出制定目录夹下的所有文件
- /// </summary>
- /// <param name="DirPath"></param>
- /// <returns></returns>
- public static string[] GetAllFilenNameByDir(string DirPath)
- {
- string[] FilesName = new string[System.IO.Directory.GetFiles(DirPath).Length];
- int i = 0;
- foreach (string file in System.IO.Directory.GetFiles(DirPath)) //列举出所有文件,添加到AL
- {
- FilesName[i] = file;
- i = i + 1;
- }
- return FilesName;
- }
- /// <summary>
- /// 测试
- /// </summary>
- /// <param name="DirPath"></param>
- /// <returns></returns>
- public static System.Collections.ArrayList GetAllFileByDir(string DirPath)
- {
- System.Collections.ArrayList AL = new System.Collections.ArrayList();
- foreach (string file in System.IO.Directory.GetFiles(DirPath)) //列举出所有文件,添加到AL
- {
- AL.Add(file);
- }
- return AL;
- //foreach (string dir in System.IO.Directory.GetDirectories(DirPath)) //列举出所有子文件夹,并对之调用GetAllFileByDir自己;
- //{
- // //GetAllFileByDir(dir, ref AL);
- //}
- // void GetAllFileByDir(string DirPath,ref ArrayList AL)
- //{
- // //列举出所有文件,添加到AL
- // foreach(string file in Directory.GetFiles(DirPath))
- // AL.Add(file);
- // //列举出所有子文件夹,并对之调用GetAllFileByDir自己;
- // foreach(string dir in Directory.GetDirectories(DirPath))
- // GetAllFileByDir(dir,ref AL);
- //}
- }
- /// <summary>
- /// 得到待打开的文件名
- /// </summary>
- /// <param name="_FileType">=null为所有文件|xml类文件="xml"|Excel文件="xls"|word文件="doc"|文本文件="txt")执行文件="exe"|图形文件="jpg|C#类文件=cs|BIN文件=bin</param>
- /// <returns></returns>
- public static string GetFileOpenName(string _FileType)
- {
- string strFileName = "";
- System.Windows.Forms.OpenFileDialog MyOpenFileDialog = new System.Windows.Forms.OpenFileDialog();
- string strFilter = "所有文件(*.*)|*.*";
- if (_FileType == null)
- {
- MyOpenFileDialog.Filter = strFilter; //当前目录的显示文件类型过滤
- MyOpenFileDialog.FilterIndex = 1;
- }
- else
- {
- #region 文件类型的字符串
- switch (_FileType.ToLower())
- {
- case "xml":
- _FileType = "xml文件(*.xml)|*.xml";
- break;
- case "xls":
- _FileType = "Excel文件(*.xls)|*.xls";
- break;
- case "doc":
- _FileType = "word类文件(*.doc)|*.doc";
- break;
- case "cs":
- _FileType = "C#类文件(*.cs)|*.cs";
- break;
- case "jpg":
- _FileType = "图形文件(*.jpg)|*.jpg";
- break;
- case "txt":
- _FileType = "文本文件(*.txt)|*.txt";
- break;
- case "exe":
- _FileType = "执行文件(*.exe)|*.exe";
- break;
- case "bin":
- _FileType = "BIN文件(*.bin)|*.bin";
- break;
- }
- #endregion
- strFilter = strFilter + "|" + _FileType;
- MyOpenFileDialog.Filter = strFilter; //当前目录的显示文件类型过滤
- MyOpenFileDialog.FilterIndex = 2;
- }
- if (MyOpenFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
- {
- return null;
- }
- else
- {
- strFileName = MyOpenFileDialog.FileName;
- return strFileName;
- }
- }
- /// <summary>
- /// 得到待保存的文件名
- /// </summary>
- /// <param name="_FileType">xml类文件="xml"|Excel文件="xls"|word文件="doc"|文本文件="txt")执行文件="exe"|图形文件="jpg|C#类文件=cs|BIN文件=bin</param>
- /// <returns></returns>
- public static string GetFileSaveName(string _FileType)
- {
- string strFileName = "";
- System.Windows.Forms.SaveFileDialog MySaveFileDialog = new System.Windows.Forms.SaveFileDialog();
- string strFilter = "所有文件(*.*)|*.*";
- if (_FileType == null)
- {
- MySaveFileDialog.Filter = strFilter; //当前目录的显示文件类型过滤
- MySaveFileDialog.FilterIndex = 1;
- }
- else
- {
- #region 文件类型的字符串
- switch (_FileType.ToLower())
- {
- case "xml":
- _FileType = "xml文件(*.xml)|*.xml";
- break;
- case "xls":
- _FileType = "Excel文件(*.xls)|*.xls";
- break;
- case "doc":
- _FileType = "word类文件(*.doc)|*.doc";
- break;
- case "cs":
- _FileType = "C#类文件(*.cs)|*.cs";
- break;
- case "jpg":
- _FileType = "图形文件(*.jpg)|*.jpg";
- break;
- case "txt":
- _FileType = "文本文件(*.txt)|*.txt";
- break;
- case "exe":
- _FileType = "执行文件(*.exe)|*.exe";
- break;
- case "bin":
- _FileType = "BIN文件(*.bin)|*.bin";
- break;
- }
- #endregion
- strFilter = strFilter + "|" + _FileType;
- MySaveFileDialog.Filter = strFilter; //当前目录的显示文件类型过滤
- MySaveFileDialog.FilterIndex = 2;
- }
- if (MySaveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
- {
- return null;
- }
- else
- {
- strFileName = MySaveFileDialog.FileName;
- return strFileName;
- }
- }
- /// <summary>
- /// 文件改名
- /// </summary>
- /// <param name="_strOldFileName">老文件名</param>
- /// <param name="_strPostfix">后缀</param>
- /// <returns></returns>
- public static string GetFileChangeName(string _strOldFileName, string _strPostfix)
- {
- //string _strFileName = Lonty.UC.GetFileNameString.SaveName("xls");
- if (_strOldFileName == "") { return null; }
- int x1 = _strOldFileName.LastIndexOf("\\");
- string Path = _strOldFileName.Substring(0, x1 + 1);
- string SaveFileName = _strOldFileName.Substring(x1 + 1, _strOldFileName.Length - x1 - 5) + _strPostfix;
- string strFileTypeName = _strOldFileName.Substring(_strOldFileName.Length - 4, 4).ToLower();
- SaveFileName = Path + SaveFileName + strFileTypeName;
- return SaveFileName;
- //if (myExcel_1.App_ExcelSave(SaveFileName))
- //{
- // MessageBox.Show("文件<" + SaveFileName + ">保存成功!");
- //}
- //else
- //{
- // MessageBox.Show("文件<" + SaveFileName + ">保存失败!");
- //}
- }
- /// <summary>
- /// 获取没有目录路径的文件名
- /// </summary>
- /// <param name="_strOldFileName"></param>
- /// <param name="_b1">是否包含文件扩展名,true = 包含文件扩展名</param>
- /// <returns>不含目录路径的文件名</returns>
- public static string GetFileNameNoPath(string _strOldFileName, bool _b1)
- {
- if (_strOldFileName == "") { return null; }
- try
- {
- int x1 = _strOldFileName.LastIndexOf("\\");
- string Path = _strOldFileName.Substring(0, x1 + 1);
- string SaveFileName = _strOldFileName.Substring(x1 + 1, _strOldFileName.Length - x1 - 5);
- if (_b1)
- {
- string strFileTypeName = _strOldFileName.Substring(_strOldFileName.Length - 4, 4).ToLower();
- SaveFileName = SaveFileName + strFileTypeName;
- }
- return SaveFileName;
- }
- catch { return null; }
- }
- /// <summary>
- /// 把文件名中最后的的字符"PARAPOSDEF".改为"PARA" ,扩展名不变
- /// </summary>
- /// <param name="_strFileName"></param>
- /// <returns></returns>
- public static string GetFileReName_PARAPOSDEF_PARA(string _strFileName)
- {
- //string _strFileName = Lonty.UC.GetFileNameString.SaveName("xls");
- if (_strFileName == "") { return null; }
- int x1 = _strFileName.LastIndexOf("\\");
- int x2 = _strFileName.LastIndexOf("PARAPOSDEF");
- if (x2 == -1)
- {
- MessageBox.Show("打开的文件名中不包含PARAPOSDEF等字符,不符合规范!");
- x2 = _strFileName.Length;
- }
- String Path = _strFileName.Substring(0, x1 + 1);
- //String SaveFileName = strFileName.Substring(x1 + 1, x2 - x1 -5) + "_PARA.xml";
- String SaveFileName = _strFileName.Substring(x1 + 1, x2 - x1 - 2) + "_PARA";
- string strFileTypeName = _strFileName.Substring(_strFileName.Length - 4, 4).ToLower();
- SaveFileName = SaveFileName + strFileTypeName;
- SaveFileName = Path + SaveFileName;
- return SaveFileName;
- //if (myExcel_1.App_ExcelSave(SaveFileName))
- //{
- // MessageBox.Show("文件<" + SaveFileName + ">保存成功!");
- //}
- //else
- //{
- // MessageBox.Show("文件<" + SaveFileName + ">保存失败!");
- //}
- }
- /// <summary>
- /// 将字符串保存为文件(汉字显示方式),文件名在此方法中将打开输入文件名的对话框
- /// </summary>
- /// <param name="_strData">要保存的字符串数据</param>
- /// <param name="_bAppend">true=在文件原有内容的基础上添加 false =先清空,再写</param>
- /// <returns></returns>
- public static bool StringToSaveTxtFile(string _strData, bool _bAppend)
- {
- if (_strData == "")
- {
- System.Windows.Forms.MessageBox.Show("内容为空,不保存");
- return false;
- }
- string FileName = SuperTools.FileTools.GetFileSaveName("txt");
- //如果文件名没有扩展名就加上的扩展名
- if (FileName.Length < 4 || FileName.Substring(FileName.Length - 4, 4).ToLower() != ".txt")
- {
- FileName += ".txt";
- }
- //*************************************************************
- try
- {
- //System.IO.Stream MyStream = System.IO.File.OpenWrite(fName);
- //using (System.IO.StreamWriter MyWriter = new System.IO.StreamWriter(MyStream, Encoding.GetEncoding("gb2312")))
- using (System.IO.StreamWriter MyWriter = new System.IO.StreamWriter(FileName, _bAppend, Encoding.GetEncoding("gb2312")))
- {
- //strData = richTextBoxFor_ultraGrid_Init.Text;
- MyWriter.Write(_strData);
- MyWriter.Close();
- System.Windows.Forms.MessageBox.Show("OK!文件保存完毕");
- return true;
- }
- }
- catch (System.IO.IOException ex)
- {
- System.Windows.Forms.MessageBox.Show(ex.Message, "Simple Editor",
- System.Windows.Forms.MessageBoxButtons.OK,
- System.Windows.Forms.MessageBoxIcon.Exclamation);
- return false;
- }//try
- catch (Exception exp)
- {
- System.Console.WriteLine("保存文件错误:" + exp.Message);
- return false;
- } //try
- }
- /// <summary>
- /// 写数据包信息到BIN文件
- /// </summary>
- /// <param name="_byteData">要保存的Byte数组数据</param>
- /// <param name="_UpdateCount">Bin文件计数 </param>
- public static bool ByteToSaveBinFile(byte[] _byteData, long _UpdateCount)
- {
- if (_byteData == null)
- {
- return false;
- }
- string _RunPath = System.Environment.CurrentDirectory; //当前windows系统环境目录
- _RunPath = System.AppDomain.CurrentDomain.BaseDirectory; //当前应用程序的目录
- //string str8 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;//获取模块的完整路径。
- try
- {
- if (System.IO.Directory.Exists(_RunPath + "\\log") == false)
- {
- System.IO.Directory.CreateDirectory(_RunPath + "\\log");
- }
- string FileName;
- string strCurrentTime = System.DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_ms");
- FileName = _RunPath + "\\log\\Log_" + _UpdateCount.ToString("00000") + "_" + strCurrentTime + ".Bin";
- try
- {
- //System.IO.Stream MyStream = System.IO.File.OpenWrite(fName);
- //using (System.IO.StreamWriter MyWriter = new System.IO.StreamWriter(MyStream, Encoding.GetEncoding("gb2312")))
- //using (System.IO.StreamWriter MyWriter = new System.IO.StreamWriter(FileName, _bAppend, Encoding.GetEncoding("gb2312")))
- using (System.IO.FileStream FileStreamInf = new System.IO.FileStream(FileName, System.IO.FileMode.OpenOrCreate))
- {
- FileStreamInf.Write(_byteData, 0, _byteData.Length);
- FileStreamInf.Close();
- //System.Windows.Forms.MessageBox.Show("OK!文件保存完毕");
- return true;
- }
- }
- catch (System.IO.IOException ex)
- {
- System.Windows.Forms.MessageBox.Show(ex.Message, "Lonty",
- System.Windows.Forms.MessageBoxButtons.OK,
- System.Windows.Forms.MessageBoxIcon.Exclamation);
- return false;
- }//try
- catch (Exception exp)
- {
- System.Console.WriteLine("保存日志文件文件错误:" + exp.Message);
- return false;
- } //catch
- }
- catch (System.Exception exp)
- {
- System.Console.WriteLine("写LOG日志文件文件错误:" + exp.Message);
- return false;
- }
- }
- /// <summary>
- /// 写日志信息到日志文件
- /// </summary>
- /// <param name="_strData">要保存的字符串数据</param>
- /// <param name="_bAppend">true=在文件原有内容的基础上添加 false =先清空,再写 </param>
- public static bool StringToSaveLogFile(string _strData, bool _bAppend)
- {
- if (_strData == "")
- {
- return false;
- }
- string _RunPath = System.Environment.CurrentDirectory; //当前windows系统环境目录
- _RunPath = System.AppDomain.CurrentDomain.BaseDirectory; //当前应用程序的目录
- //string str8 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;//获取模块的完整路径。
- try
- {
- if (System.IO.Directory.Exists(_RunPath + "\\log") == false)
- {
- System.IO.Directory.CreateDirectory(_RunPath + "\\log");
- }
- string FileName;
- string CurrentAppName = "";
- if (_bAppend)
- {
- string s1 = System.Windows.Forms.Application.ExecutablePath;
- CurrentAppName = SuperTools.FileTools.GetFileNameNoPath(s1, false);
- }
- else
- {
- CurrentAppName = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ms");
- }
- FileName = _RunPath + "\\log\\Log_" + CurrentAppName + ".log";
- try
- {
- //System.IO.Stream MyStream = System.IO.File.OpenWrite(fName);
- //using (System.IO.StreamWriter MyWriter = new System.IO.StreamWriter(MyStream, Encoding.GetEncoding("gb2312")))
- using (System.IO.StreamWriter MyWriter = new System.IO.StreamWriter(FileName, _bAppend, Encoding.GetEncoding("gb2312")))
- {
- string strCurrentTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ms");
- MyWriter.WriteLine(strCurrentTime + ":" + _strData);
- MyWriter.WriteLine("--------------------------------------------------------------------------------");
- MyWriter.WriteLine("\r\n");
- MyWriter.Close();
- //System.Windows.Forms.MessageBox.Show("OK!文件保存完毕");
- return true;
- }
- }
- catch (System.IO.IOException ex)
- {
- System.Windows.Forms.MessageBox.Show(ex.Message, "Lonty",
- System.Windows.Forms.MessageBoxButtons.OK,
- System.Windows.Forms.MessageBoxIcon.Exclamation);
- return false;
- }//try
- catch (Exception exp)
- {
- System.Console.WriteLine("保存日志文件文件错误:" + exp.Message);
- return false;
- } //catch
- }
- catch (System.Exception exp)
- {
- System.Console.WriteLine("写LOG日志文件文件错误:" + exp.Message);
- return false;
- }
- }
- /// <summary>
- /// <para>更改文件的只读属性,以便可以修改了内容的文件可以覆盖</para>
- /// </summary>
- /// <param name="filePath">目录路径The fully qualified path to the file.</param>
- public static void ChangeFileAttributesToWritable(string filePath)
- {
- //namespace Microsoft.Practices.EnterpriseLibrary.Common
- //ArgumentValidation.CheckForNullReference(filePath, "filePath");
- if (!System.IO.File.Exists(filePath))
- {
- return;
- }
- System.IO.FileAttributes attributes = System.IO.File.GetAttributes(filePath);
- System.IO.FileAttributes attr = attributes | System.IO.FileAttributes.ReadOnly;
- if (attr == attributes)
- {
- attributes ^= System.IO.FileAttributes.ReadOnly;
- System.IO.File.SetAttributes(filePath, attributes);
- }
- }
- /// <summary>
- /// <para>检查文件是否只读</para>
- /// </summary>
- /// <param name="filePath">目录路径The fully qualified path to the file.</param>
- public static bool IsFileReadOnly(string filePath)
- {
- if (!System.IO.File.Exists(filePath))
- {
- return false;
- }
- System.IO.FileAttributes attributes = System.IO.File.GetAttributes(filePath);
- System.IO.FileAttributes attr = attributes | System.IO.FileAttributes.ReadOnly;
- if (attr == attributes)
- {
- return true;
- }
- return false;
- }
- /*
- /// <summary>
- /// <para>Creat a zero byte length file in the specified path.</para>
- /// </summary>
- /// <param name="filePath">
- /// <para>The absolute path to the file to create.</para>
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <para><paramref name="filePath"/> is a <see langword="null"/> reference (Nothing in Visual Basic).</para>
- /// </exception>
- /// <exception cref="UnauthorizedAccessException">
- /// <para>The caller does not have the required permission.</para>para>
- /// <para>-or-</para>
- /// <para><paramref name="filePath"/> specified a file that is read-only.</para>
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <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>
- /// </exception>
- /// </exception>
- /// <exception cref="ArgumentNullException">
- /// <para><paramref name="filePath"/> is in an invalid format.</para>
- /// </exception>
- /// <seealso cref="System.IO.File.Create(string)"/>
- ///
-
- */
- /// <summary>
- /// 创建空文件
- /// </summary>
- /// <param name="filePath"></param>
- public static void CreateZeroByteFile(string filePath)
- {
- //namespace Microsoft.Practices.EnterpriseLibrary.Common
- //ArgumentValidation.CheckForNullReference(filePath, "filePath");
- using (System.IO.File.Create(filePath))
- {
- }
- }
- /// <summary>
- /// 在程序中运行批处理命令
- /// </summary>
- /// <param name="strCMD"></param>
- /// <param name="strCMD_s"></param>
- public static void RunBATcommand(string strCMD, string strCMD_s)
- {
- //声明一个程序信息类
- System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();
- Info.FileName = strCMD; //设置外部程序名
- Info.Arguments = strCMD_s; //设置外部程序的启动参数(命令行参数)为test.txt
- Info.WorkingDirectory = "C:\\DataLog\\"; //设置外部程序工作目录为 C:\DataLog
- System.Diagnostics.Process Proc; //声明一个程序类
- try //启动外部程序
- {
- Proc = System.Diagnostics.Process.Start(Info);
- }
- catch (System.ComponentModel.Win32Exception e)
- {
- Console.WriteLine("系统找不到指定的批处理文件。\r{0}", e);
- return;
- }
- Console.WriteLine("外部程序的开始执行时间:{0}", Proc.StartTime); //打印出外部程序的开始执行时间
- Proc.WaitForExit(8000); //等待3秒钟
- //如果这个外部程序没有结束运行则对其强行终止
- if (Proc.HasExited == false)
- {
- Console.WriteLine("由主程序强行终止外部程序的运行!");
- Proc.Kill();
- }
- else
- {
- Console.WriteLine("由外部程序正常退出!");
- }
- Console.WriteLine("外部程序的结束运行时间:{0}", Proc.ExitTime);
- Console.WriteLine("外部程序在结束运行时的返回值:{0}", Proc.ExitCode);
- }
- }
- #endregion
- }
|