2012年1月17日 星期二

【转】sqlite fts3自定义分词器

     sqlite3通过使用fts3虚表支持全文搜索,默认支持simple和porter两种分词器,并提供了接口来自定义分词器。这里我们利用mmseg来构造自定义的中文分词器。
      虽然sqlite在fts3_tokenizer.h中提供了各种接口供用户自定义分词器,但其并未提供c函数供用户来注册自定义的分词器,分词器的注册必须使用sql语句来完成。
    SELECT fts3_tokenizer(<tokenizer-name>, <sqlite3_tokenizer_module ptr>);
    其中tokenizer-name是分词器的名称,sqlite3_tokenizer_module ptr只一个指向sqlite3_tokenizer_module结构的指针并且编码为SQL blob。下面是官方给出的注册函数:
int registerTokenizer(
        sqlite3 *db,
        char *zName,
        const sqlite3_tokenizer_module *p
        ){
    int rc;
    sqlite3_stmt *pStmt;
    const char *zSql = "SELECT fts3_tokenizer(?, ?)";
    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
    if( rc!=SQLITE_OK ){
        return rc;
    }
    sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
    sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
    sqlite3_step(pStmt);
    return sqlite3_finalize(pStmt);
}

    要想实现自定义的分词器,最关键的时是得到指向sqlite3_tokenizer_module结构的一个指针,sqlite3_tokenizer_module结构体定义如下:
struct sqlite3_tokenizer_module {
int iVersion; //版本号,必须设置为0
int (*xCreate)( //创建虚表时自动调用并创建分词器
    int argc,                          
    const char *const*argv,           
    sqlite3_tokenizer **ppTokenizer   
);
int (*xDestroy)(sqlite3_tokenizer *pTokenizer); //数据库连接关闭时自动调用,用于销毁资源
int (*xOpen)( //插入数据或检索时自动调用以进行分词
    sqlite3_tok enizer *pTokenizer,     
    const char *pInput, int nBytes,    
    sqlite3_tokenizer_cursor **ppCursor
);

int (*xClose)(sqlite3_tokenizer_cursor *pCursor); //分词结果提取完毕后自动调用

int (*xNext)( //逐个提取分词结果
    sqlite3_tokenizer_cursor *pCursor,  
    const char **ppToken, int *pnBytes,
    int *piStartOffset,
    int *piEndOffset,
    int *piPosition
);
};
    有几点需要注意的是:
    1 分词引擎使用sql语句注册意味着每建立一个sqlite连接都必须注册一次分词器,对于需要使用词库的中文分词器来说也意味着巨大的内存消耗。
    2 在检索时分词结果的提取和语义的解析式交替进行的。例如我们搜索"kanif OR sqlite"的时候,引擎先将全部传入到分词器,在调用一次next获取到词 kanif后,在将词sqlite传入到分词器,直到全部解析完毕。
    3 由于中文分词本身的特殊性,例如"北京市"很有可能视为一个完整的词,这样在搜索"北京"的时候就无法获取到结果。如果分词器支持将"北京市"切分为"北 京市"和"北京"或者将十一月切分为"11月"和"十一",那么需注意(*xNext)函数中的piStartOffset和piEndOffset参 数。经测试在插入数据的时候这两个参数无实际用途,但在查询的时候这两个参数决定了下一次的输入串。

附:
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>

#include "fts3_tokenizer.h"
#include "mmseg/mmseg.cpp"

static bool loadDic = true;

typedef struct cus_tokenizer {
sqlite3_tokenizer base;
} cus_tokenizer;

typedef struct cus_tokenizer_cursor {
sqlite3_tokenizer_cursor base;
char *pInput;
int nBytes;
int iToken;
char *pToken;
rmmseg::Algorithm *pAlgor;
} cus_tokenizer_cursor;

void initmmseg(void){
    if(!loadDic)
        return;
    mmseg_load_words("chars.dic");
    mmseg_load_words("words.dic");
    loadDic = False;
}

static int cusCreate(
int argc, const char * const *argv,
sqlite3_tokenizer **ppTokenizer
){
cus_tokenizer *t;
t = (cus_tokenizer *) sqlite3_malloc(sizeof(*t));
if( t==NULL ) return SQLITE_NOMEM;
memset(t, 0, sizeof(*t));
initmmseg();
*ppTokenizer = &t->base;
return SQLITE_OK;
}

static int cusDestroy(sqlite3_tokenizer *pTokenizer){
sqlite3_free(pTokenizer);
return SQLITE_OK;
}

static int cusOpen(
sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
const char *pInput, int nBytes,        /* String to be tokenized */
sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
){
cus_tokenizer_cursor *c;
if(pInput == 0){
    nBytes = 0;
}else if(nBytes < 0)
     nBytes = (int)strlen(pInput);

c = (cus_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
if(c == NULL)
      return SQLITE_NOMEM;

c->iToken = c->nBytes = 0;
c->pInput = c->pToken = NULL;
c->pAlgor = mmseg_algor_create(pInput, nBytes);
c->nBytes = nBytes;
*ppCursor = &c->base;
return SQLITE_OK;
}

static int cusClose(sqlite3_tokenizer_cursor *pCursor){
cus_tokenizer_cursor *c = (cus_tokenizer_cursor *) pCursor;
if(c->pInput != NULL){
    sqlite3_free(c->pInput);
}
if(c->pToken != NULL){
    sqlite3_free(c->pToken);
}
if(c->pAlgor != NULL){
    mmseg_algor_destroy(c->pAlgor);
}
c->pInput = c->pToken = NULL;
c->pAlgor = NULL;
sqlite3_free(c);
return SQLITE_OK;
}

/*
1 sqlite只有在插入数据的时候才使用cursor遍历
2 在进行数据查询时,只会进入一次,然后使用piStartOffset与piEndOffset根据原始串重新生成查询串
*/
static int cusNext(
sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by cusOpen */
const char **ppToken,               /* OUT: *ppToken is the token text */
int *pnBytes,                       /* OUT: Number of bytes in token */
int *piStartOffset,                 /* OUT: Starting offset of token */
int *piEndOffset,                   /* OUT: Ending offset of token */
int *piPosition                     /* OUT: Position integer of token */
){
cus_tokenizer_cursor *c = (cus_tokenizer_cursor *) pCursor;
cus_tokenizer *t = (cus_tokenizer *) pCursor->pTokenizer;
if(c->pToken != NULL){
    sqlite3_free(c->pToken);
    c->pToken = NULL;
}
struct Token token = mmseg_next_token(c->pAlgor);
if(token.length != 0 ){
    int l = token.length;
    c->pToken = (char *)sqlite3_malloc(l+1);
    if(c->pToken == NULL)
        return SQLITE_NOMEM;
    c->pToken[l] = 0;
    memcpy(c->pToken, token.text, l);
    *ppToken = c->pToken;
    *pnBytes = l;
    *piStartOffset = token.offset;
    *piEndOffset = token.offset + token.length;
    *piPosition = c->iToken++;
    return SQLITE_OK;
}
//一般来说只有插入数据时才会进入到这里
return SQLITE_DONE;
}
static const sqlite3_tokenizer_module cusTokenizerModule = {
0,
cusCreate,
cusDestroy,
cusOpen,
cusClose,
cusNext,
};

int registerTokenizer(
        sqlite3 *db,
        char *zName,
        const sqlite3_tokenizer_module *p
        ){
    int rc;
    sqlite3_stmt *pStmt;
    const char *zSql = "SELECT fts3_tokenizer(?, ?)";
    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
    if( rc!=SQLITE_OK ){
        return rc;
    }
    sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
    sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
    sqlite3_step(pStmt);
    return sqlite3_finalize(pStmt);
}

int main(){
    const sqlite3_tokenizer_module *ptr = &cusTokenizerModule;
    sqlite3 *pDB;
    sqlite3_stmt * stmt;
    char * errMsg = NULL;
    const char *zTail;

    int rc = sqlite3_open("test.sqlite3", &pDB);
    if(rc){
        printf("create error. %s\n",sqlite3_errmsg(pDB));
        return rc;
    }
    char token_name[] = "custoken";
    registerTokenizer(pDB, token_name, ptr);

    rc = sqlite3_exec(pDB, "CREATE VIRTUAL TABLE foo USING fts3(tokenize=custoken)", 0, 0, &errMsg);
    if(rc != SQLITE_OK){
        printf("create virtual error, %s\n", errMsg);
    if(rc != SQLITE_OK){
        printf("create virtual error, %s\n", errMsg);
        return rc;
    }
    rc = sqlite3_exec(pDB, "INSERT INTO foo VALUES('\xe5\x8c\x97\xe4\xba\xac\xe5\xb8\x82')", 0, 0, &errMsg);
    if(rc != SQLITE_OK){
        printf("insert value error, %s\n", errMsg);
        return rc;
    }
    int nrow = 0, ncolumn = 0;
    char **azResult; //二维数组存放结果
    sqlite3_get_table(pDB , "SELECT * FROM foo WHERE content MATCH '\xe5\x8c\x97\xe4\xba\xac\xe5\xb8\x82'" , &azResult , &nrow , &ncolumn , &errMsg );
    int i = 0 ;
    printf( "row:%d column=%d \n" , nrow , ncolumn );
    printf( "\nThe result of querying is : \n" );
    for( i=0 ; i<( nrow + 1 ) * ncolumn ; i++ )
          printf( "azResult[%d] = %s\n", i , azResult[i] );
    sqlite3_free_table( azResult );
    sqlite3_close(pDB);
    return 0;
}

摘自:http://hi.baidu.com/xjtukanif/blog/item/8e7a4ea5362abf99d14358e2.html

2012年1月12日 星期四

[转载]delphi中register, pascal, cdecl, stdcall, safecall

注: 使用错误,或者在该加的地方没有加,可能会出现"privileged instruction"错误,或者地址访问错误。

常见的调用惯例有register, pascal, cdecl, stdcall, safecall。函数的调用管理决定了参数如何传递给子过程,并从堆栈中退出,以及寄存器在参数传递中的使用,错误和异常的处理。Delphi中默认的调用惯例是register。
1) register和pascal:参数从左向右传递,也就是说最左边的参数最先求值并传入,最右边的参数最后求值和传入。cdecl,stdcall和safecall则按从右向左方向。
2) 对于除cdecl之外的所有调用惯例,函数/过程在返回的时候要把堆栈中的参数退栈。对cdecl惯例,调用者在被调用的过程返回后执行参数退栈操作
3) register调用惯例最多能用3个CPU寄存器来传递参数,而其它调用惯例只能通过堆栈来传递参数
4) safecall调用惯例实现了异常的防火墙。在Windows上实现了跨进程的COM错误通知机制。
5) register调用效率最高,因为它避免了堆栈的创建。Delphi中published属性必须是register。
6) cdecl常用于调用C/C++编写的共享库中的函数;但是,如果要调用外部代码,那么一般要用stdcall和safecall
7) 在Windows上,系统的API都是stdcall和safecall;在其它操作系统上通常用cdecl(注意:stdcall比cdecl效率要高)
8) 在dual-interface(双接口)方法中必须用safecall惯例。
9) pascal惯例是为了向后兼容;near/far/export用于16位Window编程中的函数调用,在32位的应用程序中不发挥作用,仅仅是为了向后兼容。
下表进行了总结:

Calling conventions Parameter order Clean-up Passes parameters in registers?
register Left-to-right Routine Yes
pascal Left-to-right Routine No
cdecl Right-to-left Caller No
stdcall Right-to-left Routine No
safecall Right-to-left Routine No

参考资料:Delphi帮助文档

摘自:http://blog.sina.com.cn/s/blog_9048a0c40100uin9.html

2011年12月16日 星期五

【转】jquery的checked以及disabled

下面只提到checked,其实disabled在jquery里的用法和checked是一模一样的

下边两种写法没有任何区别 只是少了些代码而已...

-----------------------------------------------------------
<input id="cb1" type="checkbox" checked />
<input id="cb2" type="checkbox" checked="checked" />

--------------------------------------------------------------

jquery判断checked的三种方法:

.attr('checked'):   //看版本1.6+返回:"checked"或"undefined" ;1.5-返回:true或false
.prop('checked'): //16+:true/false
.is(':checked'):    //所有版本:true/false//别忘记冒号哦

jquery赋值checked的几种写法:

所有的jquery版本都可以这样赋值:

// $("#cb1").attr("checked","checked");
// $("#cb1").attr("checked",true);

jquery1.6+:prop的4种赋值:

// $("#cb1").prop("checked",true);//很简单就不说了哦
// $("#cb1").prop({checked:true}); //map键值对
// $("#cb1").prop("checked",function(){
return true;//函数返回true或false
});

//记得还有这种哦:$("#cb1").prop("checked","checked");

更多参考:http://api.jquery.com/prop/

上代码 大家可以随便测试:(你是懒人么-_-)

jquery1.6以后才支持prop的哦

新建一个text复制内容进去  后缀名改成html

<html>
<head>
<title>测试</title>
<style type="text/css">

</style>
<!--1.62可以修改1.42 1.52 1.7来测试-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(
function(){
//判断checked
       // var a=$("#cb1").attr('checked'); //看版本1.6+返回:"checked"或"undefined" ;1.5-返回:true或false
       // var b=$("#cb1").prop('checked'); //1.6+:true/false
       var c=$("#cb1").is(':checked'); //所有版本:true/false
       // alert(a);
       // alert(b);
alert(c);

//赋值 前两个所有的jquery版本都支持 prop只有jquery1.6+支持
       // $("#cb1").attr("checked","checked");//1.5-
       // $("#cb1").attr("checked",true);//1.5-
       //   $("#cb1").prop("checked","checked");//1.6+(整理的时候把这个忘记啦)
       //    $("#cb1").prop("checked",true);//1.6+
       // $("#cb1").prop({checked:true});//1.6+
      // $("#cb1").prop("checked",function(){
       // return true;//1.6+
       // });
})();

</script>
</head>
<body>
<!--赋值的时候记得去掉checked-->
<input id="cb1" type="checkbox" checked />
<input id="cb2" type="checkbox" checked="checked"/>
</body>
</html>

摘自:http://www.cnblogs.com/0banana0/archive/2011/11/16/2251855.html

2011年12月15日 星期四

【转】PHP导入导出Excel方法

PHP导入导出Excel方法  

原作者:冰山上的播客
看 到这篇文章的时候,很是惊讶原作者 的耐心,虽然我们在平时用的也有一些,但没有作者列出来的全,写excel的时候,我用过pear的库,也用过pack压包的头,同样那些利用 smarty等作的简单替换xml的也用过,csv的就更不用谈了。呵呵。(COM方式不讲了,这种可读的太多了,我也写过利用wps等进行word等的 生成之类的文章 )
但是在读的时候,只用过一种,具体是什么忘了,要回去翻代码了。因为采用的是拿来主义,记不住。
原文地址:http://xinsync.xju.edu.cn/index.php/archives/3858
原文内容:

最近因项目需要,需要开发一个模块,把系统中的一些数据导出成Excel,修改后再导回系统。就趁机对这个研究了一番,下面进行一些总结。
基本上导出的文件分为两种:
1:类Excel格式,这个其实不是传统意义上的Excel文件,只是因为Excel的兼容能力强,能够正确打开而已。修改这种文件后再保存,通常会提示你是否要转换成Excel文件。
优点:简单。
缺点:难以生成格式,如果用来导入需要自己分别编写相应的程序。
2:Excel格式,与类Excel相对应,这种方法生成的文件更接近于真正的Excel格式。

如果导出中文时出现乱码,可以尝试将字符串转换成gb2312,例如下面就把$yourStr从utf-8转换成了gb2312:
$yourStr = mb_convert_encoding(”gb2312″, “UTF-8″, $yourStr);

下面详细列举几种方法。
一、PHP导出Excel

1:第一推荐无比风骚的PHPExcel,官方网站: http://www.codeplex.com/PHPExcel
导入导出都成,可以导出office2007格式,同时兼容2003。
下载下来的包中有文档和例子,大家可以自行研究。
抄段例子出来:


PHP代码
<?php  
/** 
* PHPExcel 

* Copyright (C) 2006 - 2007 PHPExcel 

* This library is free software; you can redistribute it and/or 
* modify it under the terms of the GNU Lesser General Public 
* License as published by the Free Software Foundation; either 
* version 2.1 of the License, or (at your option) any later version. 

* This library is distributed in the hope that it will be useful, 
* but WITHOUT ANY WARRANTY; without even the implied warranty of 
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
* Lesser General Public License for more details. 

* You should have received a copy of the GNU Lesser General Public 
* License along with this library; if not, write to the Free Software 
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA 

* @category   PHPExcel 
* @package    PHPExcel 
* @copyright  Copyright (c) 2006 - 2007 PHPExcel ( http://www.codeplex.com/PHPExcel
* @license    http://www.gnu.org/licenses/lgpl.txt    LGPL 
* @version    1.5.0, 2007-10-23 
*/  
  
/** Error reporting */  
error_reporting(E_ALL);  
  
/** Include path **/  
set_include_path(get_include_path() . PATH_SEPARATOR . ‘../Classes/’);  
  
/** PHPExcel */  
include ‘PHPExcel.php’;  
  
/** PHPExcel_Writer_Excel2007 */  
include ‘PHPExcel/Writer/Excel2007.php’;  
  
// Create new PHPExcel object  
echo date(’H:i:s’) . ” Create new PHPExcel object\n”;  
$objPHPExcel = new PHPExcel();  
  
// Set properties  
echo date(’H:i:s’) . ” Set properties\n”;  
$objPHPExcel->getProperties()->setCreator(”Maarten Balliauw”);  
$objPHPExcel->getProperties()->setLastModifiedBy(”Maarten Balliauw”);  
$objPHPExcel->getProperties()->setTitle(”Office 2007 XLSX Test Document”);  
$objPHPExcel->getProperties()->setSubject(”Office 2007 XLSX Test Document”);  
$objPHPExcel->getProperties()->setDescrīption(”Test document for Office 2007 XLSX, generated using PHP classes.”);  
$objPHPExcel->getProperties()->setKeywords(”office 2007 openxml php”);  
$objPHPExcel->getProperties()->setCategory(”Test result file”);  
  
// Add some data  
echo date(’H:i:s’) . ” Add some data\n”;  
$objPHPExcel->setActiveSheetIndex(0);  
$objPHPExcel->getActiveSheet()->setCellValue(’A1′, ‘Hello’);  
$objPHPExcel->getActiveSheet()->setCellValue(’B2′, ‘world!’);  
$objPHPExcel->getActiveSheet()->setCellValue(’C1′, ‘Hello’);  
$objPHPExcel->getActiveSheet()->setCellValue(’D2′, ‘world!’);  
  
// Rename sheet  
echo date(’H:i:s’) . ” Rename sheet\n”;  
$objPHPExcel->getActiveSheet()->setTitle(’Simple’);  
  
// Set active sheet index to the first sheet, so Excel opens this as the first sheet  
$objPHPExcel->setActiveSheetIndex(0);  
  
// Save Excel 2007 file  
echo date(’H:i:s’) . ” Write to Excel2007 format\n”;  
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);  
$objWriter->save(str_replace(’.php’, ‘.xlsx’, __FILE__));  
  
// Echo done  
echo date(’H:i:s’) . ” Done writing file.\r\n”;  

 

2、使用pear的Spreadsheet_Excel_Writer类
下载地址: http://pear.php.net/package/Spreadsheet_Excel_Writer
此类依赖于OLE,下载地址:http://pear.php.net/package/OLE
需要注意的是导出的Excel文件格式比较老,修改后保存会提示是否转换成更新的格式。
不过可以设定格式,很强大。


PHP代码
<?php  
require_once ‘Spreadsheet/Excel/Writer.php’;  
  
// Creating a workbook  
$workbook = new Spreadsheet_Excel_Writer();  
  
// sending HTTP headers  
$workbook->send(’test.xls’);  
  
// Creating a worksheet  
$worksheet =& $workbook->addWorksheet(’My first worksheet’);  
  
// The actual data  
$worksheet->write(0, 0, ‘Name’);  
$worksheet->write(0, 1, ‘Age’);  
$worksheet->write(1, 0, ‘John Smith’);  
$worksheet->write(1, 1, 30);  
$worksheet->write(2, 0, ‘Johann Schmidt’);  
$worksheet->write(2, 1, 31);  
$worksheet->write(3, 0, ‘Juan Herrera’);  
$worksheet->write(3, 1, 32);  
  
// Let’s send the file  
$workbook->close();  
?>  


3:利用smarty,生成符合Excel规范的XML或HTML文件
支持格式,非常完美的导出方案。不过导出来的的本质上还是XML文件,如果用来导入就需要另外处理了。
详细内容请见rardge大侠的帖子:http://bbs.chinaunix.net/viewthread.php?tid=745757

需要注意的是如果导出的表格行数不确定时,最好在模板中把”ss:ExpandedColumnCount=”5″ ss:ExpandedRowCount=”21″”之类的东西删掉。

4、利用pack函数打印出模拟Excel格式的断句符号,这种更接近于Excel标准格式,用office2003修改后保存,还不会弹出提示,推荐用这种方法。
缺点是无格式。


PHP代码
<?php  
// Send Header  
header(”Pragma: public”);  
header(”Expires: 0″);  
header(”Cache-Control: must-revalidate, post-check=0, pre-check=0″);  
header(”Content-Type: application/force-download”);  
header(”Content-Type: application/octet-stream”);  
header(”Content-Type: application/download”);;  
header(”Content-Disposition: attachment;filename=test.xls “);  
header(”Content-Transfer-Encoding: binary “);  
// XLS Data Cell  
  
xlsBOF();  
xlsWriteLabel(1,0,”My excel line one”);  
xlsWriteLabel(2,0,”My excel line two : “);  
xlsWriteLabel(2,1,”Hello everybody”);  
  
xlsEOF();  
  
function xlsBOF() {  
echo pack(”ssssss”, 0×809, 0×8, 0×0, 0×10, 0×0, 0×0);  
return;  
}  
function xlsEOF() {  
echo pack(”ss”, 0×0A, 0×00);  
return;  
}  
function xlsWriteNumber($Row, $Col, $Value) {  
echo pack(”sssss”, 0×203, 14, $Row, $Col, 0×0);  
echo pack(”d”, $Value);  
return;  
}  
function xlsWriteLabel($Row, $Col, $Value ) {  
$L = strlen($Value);  
echo pack(”ssssss”, 0×204, 8 + $L, $Row, $Col, 0×0, $L);  
echo $Value;  
return;  
}  
?>  
不过笔者在64位linux系统中使用时失败了,断句符号全部变成了乱码。  
  
5、使用制表符、换行符的方法  
制表符”\t”用户分割同一行中的列,换行符”\t\n”可以开启下一行。  
<?php  
header(”Content-Type: application/vnd.ms-execl”);  
header(”Content-Disposition: attachment; filename=myExcel.xls”);  
header(”Pragma: no-cache”);  
header(”Expires: 0″);  
/*first line*/  
echo “hello”.”\t”;  
echo “world”.”\t”;  
echo “\t\n”;  
  
/*start of second line*/  
echo “this is second line”.”\t”;  
echo “Hi,pretty girl”.”\t”;  
echo “\t\n”;  
?>  


6、使用com
如果你的PHP可以开启com模块,就可以用它来导出Excel文件


PHP代码
<?PHP  
$filename = “c:/spreadhseet/test.xls”;  
$sheet1 = 1;  
$sheet2 = “sheet2″;  
$excel_app = new COM(”Excel.application”) or Die (”Did not connect”);  
print “Application name: {$excel_app->Application->value}\n” ;  
print “Loaded version: {$excel_app->Application->version}\n”;  
$Workbook = $excel_app->Workbooks->Open(”$filename”) or Die(”Did not open $filename $Workbook”);  
$Worksheet = $Workbook->Worksheets($sheet1);  
$Worksheet->activate;  
$excel_cell = $Worksheet->Range(”C4″);  
$excel_cell->activate;  
$excel_result = $excel_cell->value;  
print “$excel_result\n”;  
$Worksheet = $Workbook->Worksheets($sheet2);  
$Worksheet->activate;  
$excel_cell = $Worksheet->Range(”C4″);  
$excel_cell->activate;  
$excel_result = $excel_cell->value;  
print “$excel_result\n”;  
#To close all instances of excel:  
$Workbook->Close;  
unset($Worksheet);  
unset($Workbook);  
$excel_app->Workbooks->Close();  
$excel_app->Quit();  
unset($excel_app);  
?>  

一个更好的例子: http://blog.chinaunix.net/u/16928/showart_387171.html

一、PHP导入Excel

1:还是用PHPExcel,官方网站: http://www.codeplex.com/PHPExcel

2:使用PHP-ExcelReader,下载地址: http://sourceforge.net/projects/phpexcelreader
举例:


PHP代码
<?php  
require_once ‘Excel/reader.php’;  
  
// ExcelFile($filename, $encoding);  
$data = new Spreadsheet_Excel_Reader();  
  
// Set output Encoding.  
$data->setOutputEncoding(’utf8′);  
  
$data->read(’ jxlrwtest.xls’);  
  
error_reporting(E_ALL ^ E_NOTICE);  
  
for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {  
for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {  
echo “\”".$data->sheets[0]['cells'][$i][$j].”\”,”;  
}  
echo “\n”;  
}  
  
?>  

摘自:http://pcwanli.blog.163.com/blog/static/45315611201011894811404/

【转】php导出导入execl(使用PHPExcel类)

php导出导入execl(使用PHPExcel类)

php导入execl

下载phpexcelreader类

http://sourceforge.net/projects/phpexcelreader/ 

demo 的execl有问题,自己创建一个。

下载下来以后按照readme上面的说法,访问example.php后缺发现如下错误:

Fatal error: require_once() [function.require]: Failed opening required 'Spreadsheet/Excel/Reader/OLERead.php' (include_path='.;\xampp\php\PEAR') in XXXX

意 思是缺少Spreadsheet/Excel/Reader/OLERead.php这个文件。但是确实是没有这个文件呀!找了找,在excel目录下发 现了oleread.inc文件,于是将Spreadsheet/Excel/Reader/OLERead.php换成oleread.inc就OK 了!

也就是将

require_once 'Spreadsheet/Excel/Reader/OLERead.php';

修改为

require_once 'oleread.inc';

即可。

另外,在example.php 中,需要修改

$data->setOutputEncoding('CP1251');

$data->setOutputEncoding('CP936');

不然的话中文将会有问题。

如果是使用繁体的话可以修改为CP950、日文是CP932,具体可参考codepage说明。

还有,其自带的 jxlrwtest.xls 可能有问题,需要修改example.php中的:

$data->read('jxlrwtest.xls');

为自己的 excel 文件名,用了一下,感觉还是不错的!

如果导入到数据库

在使用过程中还出现乱码:

本人页面和数据库都是utf-8,在取出的execl元素中都使用

   $textip = iconv("GB2312","UTF-8",$textip);

进行编码转换

这样才能正确导入mysql

php导出execl

下载php-excel类,网上一搜

里面有dome

一看便知,一般没有什么错误。

摘自:http://l2007024110.blog.163.com/blog/static/781151422010918111137399/

2011年12月13日 星期二

PHP去除数组里的空值

方法一:

由于没有去空值的数组函数,我们可以利用

array_diff()函数

array_diff ― 计算数组的差集

说明

array

array_diff

( array $array1, array $array2 [, array $ ...] )

array_diff() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意键名保留不变。

去空值的例子:

$array = array("a","b","",null,"c");

$array = array_diff($array, array(null));

即可去除.

------------------------------------

来源:http://web-studio.blog.sohu.com/142258062.html

====================

方法二:

例 $a =array("1","2","","4"); 怎么样去除 ""
<?php  function filter($var) {         if($var == '')         {                 return false;         }          return true; }  $a = array("1", "2", "", "4");  print_r(array_filter($a, "filter"));  ?>

2011年11月27日 星期日

【转】 strlen和mb_strlen区别(php获得中英文混合字符长度)

摘自:http://hi.baidu.com/anylzer/blog/item/f30559388884e8e8b311c75f.html

<?php
//测试时文件的编码方式要是UTF8
$str='中文a字1符';
echo strlen($str).'<br>';//14
echo mb_strlen($str,'utf8').'<br>';//6
echo mb_strlen($str,'gbk').'<br>';//8
echo mb_strlen($str,'gb2312').'<br>';//10
/*
结果分析:在strlen计算时,对待一个UTF8的中文字符是3个长度,所以"中文a字1符"长度是3*4+2=14
在mb_strlen计算时,选定内码为UTF8,则会将一个中文字符当作长度1来计算,所以"中文a字1符"长度是6
*/
//利用这两个函数则可以联合计算出一个中英文混排的串的占位是多少(一个中文字符的占位是2,英文字符是1)
echo (strlen($str) + mb_strlen($str,'UTF8')) / 2;
//例如 "中文a字1符" 的strlen($str)值是14,mb_strlen($str)值是6,则可以计算出"中文a字1符"的占位是10.
echo mb_internal_encoding();

PHP内置的字符串长度函数strlen无法正确处理中文字符串,它得 到的只是字符串所占的字节数。对于GB2312的中文编码,strlen得到的值是汉字个数的2倍,而对于UTF-8编码的中文,就是3倍的差异了(在 UTF-8编码下,一个汉字占3个字节)。

采用mb_strlen函数可以较好地解决这个问题。mb_strlen的用法和 strlen类似,只不过它有第二个可选参数用于指定字符编码。例如得到UTF-8的字符串$str长度,可以用 mb_strlen($str,'UTF-8')。如果省略第二个参数,则会使用PHP的内部编码。内部编码可以通过 mb_internal_encoding()函数得到。需要注意的是,mb_strlen并不是PHP核心函数,使用前需要确保在php.ini中加载 了php_mbstring.dll,即确保"extension=php_mbstring.dll"这一行存在并且没有被注释掉,否则会出现未定义函 数的问题。